##// END OF EJS Templates
patch: fix iterhunks() with trailing binary file removal...
Patrick Mezard -
r6179:36ab165a default
parent child Browse files
Show More
@@ -1,1390 +1,1393 b''
1 # patch.py - patch file parsing routines
1 # patch.py - patch file parsing routines
2 #
2 #
3 # Copyright 2006 Brendan Cully <brendan@kublai.com>
3 # Copyright 2006 Brendan Cully <brendan@kublai.com>
4 # Copyright 2007 Chris Mason <chris.mason@oracle.com>
4 # Copyright 2007 Chris Mason <chris.mason@oracle.com>
5 #
5 #
6 # This software may be used and distributed according to the terms
6 # This software may be used and distributed according to the terms
7 # of the GNU General Public License, incorporated herein by reference.
7 # of the GNU General Public License, incorporated herein by reference.
8
8
9 from i18n import _
9 from i18n import _
10 from node import *
10 from node import *
11 import base85, cmdutil, mdiff, util, context, revlog, diffhelpers
11 import base85, cmdutil, mdiff, util, context, revlog, diffhelpers
12 import cStringIO, email.Parser, os, popen2, re, sha, errno
12 import cStringIO, email.Parser, os, popen2, re, sha, errno
13 import sys, tempfile, zlib
13 import sys, tempfile, zlib
14
14
15 class PatchError(Exception):
15 class PatchError(Exception):
16 pass
16 pass
17
17
18 class NoHunks(PatchError):
18 class NoHunks(PatchError):
19 pass
19 pass
20
20
21 # helper functions
21 # helper functions
22
22
23 def copyfile(src, dst, basedir=None):
23 def copyfile(src, dst, basedir=None):
24 if not basedir:
24 if not basedir:
25 basedir = os.getcwd()
25 basedir = os.getcwd()
26
26
27 abssrc, absdst = [os.path.join(basedir, n) for n in (src, dst)]
27 abssrc, absdst = [os.path.join(basedir, n) for n in (src, dst)]
28 if os.path.exists(absdst):
28 if os.path.exists(absdst):
29 raise util.Abort(_("cannot create %s: destination already exists") %
29 raise util.Abort(_("cannot create %s: destination already exists") %
30 dst)
30 dst)
31
31
32 targetdir = os.path.dirname(absdst)
32 targetdir = os.path.dirname(absdst)
33 if not os.path.isdir(targetdir):
33 if not os.path.isdir(targetdir):
34 os.makedirs(targetdir)
34 os.makedirs(targetdir)
35
35
36 util.copyfile(abssrc, absdst)
36 util.copyfile(abssrc, absdst)
37
37
38 # public functions
38 # public functions
39
39
40 def extract(ui, fileobj):
40 def extract(ui, fileobj):
41 '''extract patch from data read from fileobj.
41 '''extract patch from data read from fileobj.
42
42
43 patch can be a normal patch or contained in an email message.
43 patch can be a normal patch or contained in an email message.
44
44
45 return tuple (filename, message, user, date, node, p1, p2).
45 return tuple (filename, message, user, date, node, p1, p2).
46 Any item in the returned tuple can be None. If filename is None,
46 Any item in the returned tuple can be None. If filename is None,
47 fileobj did not contain a patch. Caller must unlink filename when done.'''
47 fileobj did not contain a patch. Caller must unlink filename when done.'''
48
48
49 # attempt to detect the start of a patch
49 # attempt to detect the start of a patch
50 # (this heuristic is borrowed from quilt)
50 # (this heuristic is borrowed from quilt)
51 diffre = re.compile(r'^(?:Index:[ \t]|diff[ \t]|RCS file: |' +
51 diffre = re.compile(r'^(?:Index:[ \t]|diff[ \t]|RCS file: |' +
52 'retrieving revision [0-9]+(\.[0-9]+)*$|' +
52 'retrieving revision [0-9]+(\.[0-9]+)*$|' +
53 '(---|\*\*\*)[ \t])', re.MULTILINE)
53 '(---|\*\*\*)[ \t])', re.MULTILINE)
54
54
55 fd, tmpname = tempfile.mkstemp(prefix='hg-patch-')
55 fd, tmpname = tempfile.mkstemp(prefix='hg-patch-')
56 tmpfp = os.fdopen(fd, 'w')
56 tmpfp = os.fdopen(fd, 'w')
57 try:
57 try:
58 msg = email.Parser.Parser().parse(fileobj)
58 msg = email.Parser.Parser().parse(fileobj)
59
59
60 subject = msg['Subject']
60 subject = msg['Subject']
61 user = msg['From']
61 user = msg['From']
62 gitsendmail = 'git-send-email' in msg.get('X-Mailer', '')
62 gitsendmail = 'git-send-email' in msg.get('X-Mailer', '')
63 # should try to parse msg['Date']
63 # should try to parse msg['Date']
64 date = None
64 date = None
65 nodeid = None
65 nodeid = None
66 branch = None
66 branch = None
67 parents = []
67 parents = []
68
68
69 if subject:
69 if subject:
70 if subject.startswith('[PATCH'):
70 if subject.startswith('[PATCH'):
71 pend = subject.find(']')
71 pend = subject.find(']')
72 if pend >= 0:
72 if pend >= 0:
73 subject = subject[pend+1:].lstrip()
73 subject = subject[pend+1:].lstrip()
74 subject = subject.replace('\n\t', ' ')
74 subject = subject.replace('\n\t', ' ')
75 ui.debug('Subject: %s\n' % subject)
75 ui.debug('Subject: %s\n' % subject)
76 if user:
76 if user:
77 ui.debug('From: %s\n' % user)
77 ui.debug('From: %s\n' % user)
78 diffs_seen = 0
78 diffs_seen = 0
79 ok_types = ('text/plain', 'text/x-diff', 'text/x-patch')
79 ok_types = ('text/plain', 'text/x-diff', 'text/x-patch')
80 message = ''
80 message = ''
81 for part in msg.walk():
81 for part in msg.walk():
82 content_type = part.get_content_type()
82 content_type = part.get_content_type()
83 ui.debug('Content-Type: %s\n' % content_type)
83 ui.debug('Content-Type: %s\n' % content_type)
84 if content_type not in ok_types:
84 if content_type not in ok_types:
85 continue
85 continue
86 payload = part.get_payload(decode=True)
86 payload = part.get_payload(decode=True)
87 m = diffre.search(payload)
87 m = diffre.search(payload)
88 if m:
88 if m:
89 hgpatch = False
89 hgpatch = False
90 ignoretext = False
90 ignoretext = False
91
91
92 ui.debug(_('found patch at byte %d\n') % m.start(0))
92 ui.debug(_('found patch at byte %d\n') % m.start(0))
93 diffs_seen += 1
93 diffs_seen += 1
94 cfp = cStringIO.StringIO()
94 cfp = cStringIO.StringIO()
95 for line in payload[:m.start(0)].splitlines():
95 for line in payload[:m.start(0)].splitlines():
96 if line.startswith('# HG changeset patch'):
96 if line.startswith('# HG changeset patch'):
97 ui.debug(_('patch generated by hg export\n'))
97 ui.debug(_('patch generated by hg export\n'))
98 hgpatch = True
98 hgpatch = True
99 # drop earlier commit message content
99 # drop earlier commit message content
100 cfp.seek(0)
100 cfp.seek(0)
101 cfp.truncate()
101 cfp.truncate()
102 subject = None
102 subject = None
103 elif hgpatch:
103 elif hgpatch:
104 if line.startswith('# User '):
104 if line.startswith('# User '):
105 user = line[7:]
105 user = line[7:]
106 ui.debug('From: %s\n' % user)
106 ui.debug('From: %s\n' % user)
107 elif line.startswith("# Date "):
107 elif line.startswith("# Date "):
108 date = line[7:]
108 date = line[7:]
109 elif line.startswith("# Branch "):
109 elif line.startswith("# Branch "):
110 branch = line[9:]
110 branch = line[9:]
111 elif line.startswith("# Node ID "):
111 elif line.startswith("# Node ID "):
112 nodeid = line[10:]
112 nodeid = line[10:]
113 elif line.startswith("# Parent "):
113 elif line.startswith("# Parent "):
114 parents.append(line[10:])
114 parents.append(line[10:])
115 elif line == '---' and gitsendmail:
115 elif line == '---' and gitsendmail:
116 ignoretext = True
116 ignoretext = True
117 if not line.startswith('# ') and not ignoretext:
117 if not line.startswith('# ') and not ignoretext:
118 cfp.write(line)
118 cfp.write(line)
119 cfp.write('\n')
119 cfp.write('\n')
120 message = cfp.getvalue()
120 message = cfp.getvalue()
121 if tmpfp:
121 if tmpfp:
122 tmpfp.write(payload)
122 tmpfp.write(payload)
123 if not payload.endswith('\n'):
123 if not payload.endswith('\n'):
124 tmpfp.write('\n')
124 tmpfp.write('\n')
125 elif not diffs_seen and message and content_type == 'text/plain':
125 elif not diffs_seen and message and content_type == 'text/plain':
126 message += '\n' + payload
126 message += '\n' + payload
127 except:
127 except:
128 tmpfp.close()
128 tmpfp.close()
129 os.unlink(tmpname)
129 os.unlink(tmpname)
130 raise
130 raise
131
131
132 if subject and not message.startswith(subject):
132 if subject and not message.startswith(subject):
133 message = '%s\n%s' % (subject, message)
133 message = '%s\n%s' % (subject, message)
134 tmpfp.close()
134 tmpfp.close()
135 if not diffs_seen:
135 if not diffs_seen:
136 os.unlink(tmpname)
136 os.unlink(tmpname)
137 return None, message, user, date, branch, None, None, None
137 return None, message, user, date, branch, None, None, None
138 p1 = parents and parents.pop(0) or None
138 p1 = parents and parents.pop(0) or None
139 p2 = parents and parents.pop(0) or None
139 p2 = parents and parents.pop(0) or None
140 return tmpname, message, user, date, branch, nodeid, p1, p2
140 return tmpname, message, user, date, branch, nodeid, p1, p2
141
141
142 GP_PATCH = 1 << 0 # we have to run patch
142 GP_PATCH = 1 << 0 # we have to run patch
143 GP_FILTER = 1 << 1 # there's some copy/rename operation
143 GP_FILTER = 1 << 1 # there's some copy/rename operation
144 GP_BINARY = 1 << 2 # there's a binary patch
144 GP_BINARY = 1 << 2 # there's a binary patch
145
145
146 def readgitpatch(fp, firstline=None):
146 def readgitpatch(fp, firstline=None):
147 """extract git-style metadata about patches from <patchname>"""
147 """extract git-style metadata about patches from <patchname>"""
148 class gitpatch:
148 class gitpatch:
149 "op is one of ADD, DELETE, RENAME, MODIFY or COPY"
149 "op is one of ADD, DELETE, RENAME, MODIFY or COPY"
150 def __init__(self, path):
150 def __init__(self, path):
151 self.path = path
151 self.path = path
152 self.oldpath = None
152 self.oldpath = None
153 self.mode = None
153 self.mode = None
154 self.op = 'MODIFY'
154 self.op = 'MODIFY'
155 self.lineno = 0
155 self.lineno = 0
156 self.binary = False
156 self.binary = False
157
157
158 def reader(fp, firstline):
158 def reader(fp, firstline):
159 if firstline is not None:
159 if firstline is not None:
160 yield firstline
160 yield firstline
161 for line in fp:
161 for line in fp:
162 yield line
162 yield line
163
163
164 # Filter patch for git information
164 # Filter patch for git information
165 gitre = re.compile('diff --git a/(.*) b/(.*)')
165 gitre = re.compile('diff --git a/(.*) b/(.*)')
166 gp = None
166 gp = None
167 gitpatches = []
167 gitpatches = []
168 # Can have a git patch with only metadata, causing patch to complain
168 # Can have a git patch with only metadata, causing patch to complain
169 dopatch = 0
169 dopatch = 0
170
170
171 lineno = 0
171 lineno = 0
172 for line in reader(fp, firstline):
172 for line in reader(fp, firstline):
173 lineno += 1
173 lineno += 1
174 if line.startswith('diff --git'):
174 if line.startswith('diff --git'):
175 m = gitre.match(line)
175 m = gitre.match(line)
176 if m:
176 if m:
177 if gp:
177 if gp:
178 gitpatches.append(gp)
178 gitpatches.append(gp)
179 src, dst = m.group(1, 2)
179 src, dst = m.group(1, 2)
180 gp = gitpatch(dst)
180 gp = gitpatch(dst)
181 gp.lineno = lineno
181 gp.lineno = lineno
182 elif gp:
182 elif gp:
183 if line.startswith('--- '):
183 if line.startswith('--- '):
184 if gp.op in ('COPY', 'RENAME'):
184 if gp.op in ('COPY', 'RENAME'):
185 dopatch |= GP_FILTER
185 dopatch |= GP_FILTER
186 gitpatches.append(gp)
186 gitpatches.append(gp)
187 gp = None
187 gp = None
188 dopatch |= GP_PATCH
188 dopatch |= GP_PATCH
189 continue
189 continue
190 if line.startswith('rename from '):
190 if line.startswith('rename from '):
191 gp.op = 'RENAME'
191 gp.op = 'RENAME'
192 gp.oldpath = line[12:].rstrip()
192 gp.oldpath = line[12:].rstrip()
193 elif line.startswith('rename to '):
193 elif line.startswith('rename to '):
194 gp.path = line[10:].rstrip()
194 gp.path = line[10:].rstrip()
195 elif line.startswith('copy from '):
195 elif line.startswith('copy from '):
196 gp.op = 'COPY'
196 gp.op = 'COPY'
197 gp.oldpath = line[10:].rstrip()
197 gp.oldpath = line[10:].rstrip()
198 elif line.startswith('copy to '):
198 elif line.startswith('copy to '):
199 gp.path = line[8:].rstrip()
199 gp.path = line[8:].rstrip()
200 elif line.startswith('deleted file'):
200 elif line.startswith('deleted file'):
201 gp.op = 'DELETE'
201 gp.op = 'DELETE'
202 elif line.startswith('new file mode '):
202 elif line.startswith('new file mode '):
203 gp.op = 'ADD'
203 gp.op = 'ADD'
204 gp.mode = int(line.rstrip()[-6:], 8)
204 gp.mode = int(line.rstrip()[-6:], 8)
205 elif line.startswith('new mode '):
205 elif line.startswith('new mode '):
206 gp.mode = int(line.rstrip()[-6:], 8)
206 gp.mode = int(line.rstrip()[-6:], 8)
207 elif line.startswith('GIT binary patch'):
207 elif line.startswith('GIT binary patch'):
208 dopatch |= GP_BINARY
208 dopatch |= GP_BINARY
209 gp.binary = True
209 gp.binary = True
210 if gp:
210 if gp:
211 gitpatches.append(gp)
211 gitpatches.append(gp)
212
212
213 if not gitpatches:
213 if not gitpatches:
214 dopatch = GP_PATCH
214 dopatch = GP_PATCH
215
215
216 return (dopatch, gitpatches)
216 return (dopatch, gitpatches)
217
217
218 def patch(patchname, ui, strip=1, cwd=None, files={}):
218 def patch(patchname, ui, strip=1, cwd=None, files={}):
219 """apply <patchname> to the working directory.
219 """apply <patchname> to the working directory.
220 returns whether patch was applied with fuzz factor."""
220 returns whether patch was applied with fuzz factor."""
221 patcher = ui.config('ui', 'patch')
221 patcher = ui.config('ui', 'patch')
222 args = []
222 args = []
223 try:
223 try:
224 if patcher:
224 if patcher:
225 return externalpatch(patcher, args, patchname, ui, strip, cwd,
225 return externalpatch(patcher, args, patchname, ui, strip, cwd,
226 files)
226 files)
227 else:
227 else:
228 try:
228 try:
229 return internalpatch(patchname, ui, strip, cwd, files)
229 return internalpatch(patchname, ui, strip, cwd, files)
230 except NoHunks:
230 except NoHunks:
231 patcher = util.find_exe('gpatch') or util.find_exe('patch')
231 patcher = util.find_exe('gpatch') or util.find_exe('patch')
232 ui.debug('no valid hunks found; trying with %r instead\n' %
232 ui.debug('no valid hunks found; trying with %r instead\n' %
233 patcher)
233 patcher)
234 if util.needbinarypatch():
234 if util.needbinarypatch():
235 args.append('--binary')
235 args.append('--binary')
236 return externalpatch(patcher, args, patchname, ui, strip, cwd,
236 return externalpatch(patcher, args, patchname, ui, strip, cwd,
237 files)
237 files)
238 except PatchError, err:
238 except PatchError, err:
239 s = str(err)
239 s = str(err)
240 if s:
240 if s:
241 raise util.Abort(s)
241 raise util.Abort(s)
242 else:
242 else:
243 raise util.Abort(_('patch failed to apply'))
243 raise util.Abort(_('patch failed to apply'))
244
244
245 def externalpatch(patcher, args, patchname, ui, strip, cwd, files):
245 def externalpatch(patcher, args, patchname, ui, strip, cwd, files):
246 """use <patcher> to apply <patchname> to the working directory.
246 """use <patcher> to apply <patchname> to the working directory.
247 returns whether patch was applied with fuzz factor."""
247 returns whether patch was applied with fuzz factor."""
248
248
249 fuzz = False
249 fuzz = False
250 if cwd:
250 if cwd:
251 args.append('-d %s' % util.shellquote(cwd))
251 args.append('-d %s' % util.shellquote(cwd))
252 fp = util.popen('%s %s -p%d < %s' % (patcher, ' '.join(args), strip,
252 fp = util.popen('%s %s -p%d < %s' % (patcher, ' '.join(args), strip,
253 util.shellquote(patchname)))
253 util.shellquote(patchname)))
254
254
255 for line in fp:
255 for line in fp:
256 line = line.rstrip()
256 line = line.rstrip()
257 ui.note(line + '\n')
257 ui.note(line + '\n')
258 if line.startswith('patching file '):
258 if line.startswith('patching file '):
259 pf = util.parse_patch_output(line)
259 pf = util.parse_patch_output(line)
260 printed_file = False
260 printed_file = False
261 files.setdefault(pf, (None, None))
261 files.setdefault(pf, (None, None))
262 elif line.find('with fuzz') >= 0:
262 elif line.find('with fuzz') >= 0:
263 fuzz = True
263 fuzz = True
264 if not printed_file:
264 if not printed_file:
265 ui.warn(pf + '\n')
265 ui.warn(pf + '\n')
266 printed_file = True
266 printed_file = True
267 ui.warn(line + '\n')
267 ui.warn(line + '\n')
268 elif line.find('saving rejects to file') >= 0:
268 elif line.find('saving rejects to file') >= 0:
269 ui.warn(line + '\n')
269 ui.warn(line + '\n')
270 elif line.find('FAILED') >= 0:
270 elif line.find('FAILED') >= 0:
271 if not printed_file:
271 if not printed_file:
272 ui.warn(pf + '\n')
272 ui.warn(pf + '\n')
273 printed_file = True
273 printed_file = True
274 ui.warn(line + '\n')
274 ui.warn(line + '\n')
275 code = fp.close()
275 code = fp.close()
276 if code:
276 if code:
277 raise PatchError(_("patch command failed: %s") %
277 raise PatchError(_("patch command failed: %s") %
278 util.explain_exit(code)[0])
278 util.explain_exit(code)[0])
279 return fuzz
279 return fuzz
280
280
281 def internalpatch(patchobj, ui, strip, cwd, files={}):
281 def internalpatch(patchobj, ui, strip, cwd, files={}):
282 """use builtin patch to apply <patchobj> to the working directory.
282 """use builtin patch to apply <patchobj> to the working directory.
283 returns whether patch was applied with fuzz factor."""
283 returns whether patch was applied with fuzz factor."""
284 try:
284 try:
285 fp = file(patchobj, 'rb')
285 fp = file(patchobj, 'rb')
286 except TypeError:
286 except TypeError:
287 fp = patchobj
287 fp = patchobj
288 if cwd:
288 if cwd:
289 curdir = os.getcwd()
289 curdir = os.getcwd()
290 os.chdir(cwd)
290 os.chdir(cwd)
291 try:
291 try:
292 ret = applydiff(ui, fp, files, strip=strip)
292 ret = applydiff(ui, fp, files, strip=strip)
293 finally:
293 finally:
294 if cwd:
294 if cwd:
295 os.chdir(curdir)
295 os.chdir(curdir)
296 if ret < 0:
296 if ret < 0:
297 raise PatchError
297 raise PatchError
298 return ret > 0
298 return ret > 0
299
299
300 # @@ -start,len +start,len @@ or @@ -start +start @@ if len is 1
300 # @@ -start,len +start,len @@ or @@ -start +start @@ if len is 1
301 unidesc = re.compile('@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))? @@')
301 unidesc = re.compile('@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))? @@')
302 contextdesc = re.compile('(---|\*\*\*) (\d+)(,(\d+))? (---|\*\*\*)')
302 contextdesc = re.compile('(---|\*\*\*) (\d+)(,(\d+))? (---|\*\*\*)')
303
303
304 class patchfile:
304 class patchfile:
305 def __init__(self, ui, fname, missing=False):
305 def __init__(self, ui, fname, missing=False):
306 self.fname = fname
306 self.fname = fname
307 self.ui = ui
307 self.ui = ui
308 self.lines = []
308 self.lines = []
309 self.exists = False
309 self.exists = False
310 self.missing = missing
310 self.missing = missing
311 if not missing:
311 if not missing:
312 try:
312 try:
313 fp = file(fname, 'rb')
313 fp = file(fname, 'rb')
314 self.lines = fp.readlines()
314 self.lines = fp.readlines()
315 self.exists = True
315 self.exists = True
316 except IOError:
316 except IOError:
317 pass
317 pass
318 else:
318 else:
319 self.ui.warn(_("unable to find '%s' for patching\n") % self.fname)
319 self.ui.warn(_("unable to find '%s' for patching\n") % self.fname)
320
320
321 if not self.exists:
321 if not self.exists:
322 dirname = os.path.dirname(fname)
322 dirname = os.path.dirname(fname)
323 if dirname and not os.path.isdir(dirname):
323 if dirname and not os.path.isdir(dirname):
324 os.makedirs(dirname)
324 os.makedirs(dirname)
325
325
326 self.hash = {}
326 self.hash = {}
327 self.dirty = 0
327 self.dirty = 0
328 self.offset = 0
328 self.offset = 0
329 self.rej = []
329 self.rej = []
330 self.fileprinted = False
330 self.fileprinted = False
331 self.printfile(False)
331 self.printfile(False)
332 self.hunks = 0
332 self.hunks = 0
333
333
334 def printfile(self, warn):
334 def printfile(self, warn):
335 if self.fileprinted:
335 if self.fileprinted:
336 return
336 return
337 if warn or self.ui.verbose:
337 if warn or self.ui.verbose:
338 self.fileprinted = True
338 self.fileprinted = True
339 s = _("patching file %s\n") % self.fname
339 s = _("patching file %s\n") % self.fname
340 if warn:
340 if warn:
341 self.ui.warn(s)
341 self.ui.warn(s)
342 else:
342 else:
343 self.ui.note(s)
343 self.ui.note(s)
344
344
345
345
346 def findlines(self, l, linenum):
346 def findlines(self, l, linenum):
347 # looks through the hash and finds candidate lines. The
347 # looks through the hash and finds candidate lines. The
348 # result is a list of line numbers sorted based on distance
348 # result is a list of line numbers sorted based on distance
349 # from linenum
349 # from linenum
350 def sorter(a, b):
350 def sorter(a, b):
351 vala = abs(a - linenum)
351 vala = abs(a - linenum)
352 valb = abs(b - linenum)
352 valb = abs(b - linenum)
353 return cmp(vala, valb)
353 return cmp(vala, valb)
354
354
355 try:
355 try:
356 cand = self.hash[l]
356 cand = self.hash[l]
357 except:
357 except:
358 return []
358 return []
359
359
360 if len(cand) > 1:
360 if len(cand) > 1:
361 # resort our list of potentials forward then back.
361 # resort our list of potentials forward then back.
362 cand.sort(sorter)
362 cand.sort(sorter)
363 return cand
363 return cand
364
364
365 def hashlines(self):
365 def hashlines(self):
366 self.hash = {}
366 self.hash = {}
367 for x in xrange(len(self.lines)):
367 for x in xrange(len(self.lines)):
368 s = self.lines[x]
368 s = self.lines[x]
369 self.hash.setdefault(s, []).append(x)
369 self.hash.setdefault(s, []).append(x)
370
370
371 def write_rej(self):
371 def write_rej(self):
372 # our rejects are a little different from patch(1). This always
372 # our rejects are a little different from patch(1). This always
373 # creates rejects in the same form as the original patch. A file
373 # creates rejects in the same form as the original patch. A file
374 # header is inserted so that you can run the reject through patch again
374 # header is inserted so that you can run the reject through patch again
375 # without having to type the filename.
375 # without having to type the filename.
376
376
377 if not self.rej:
377 if not self.rej:
378 return
378 return
379 if self.hunks != 1:
379 if self.hunks != 1:
380 hunkstr = "s"
380 hunkstr = "s"
381 else:
381 else:
382 hunkstr = ""
382 hunkstr = ""
383
383
384 fname = self.fname + ".rej"
384 fname = self.fname + ".rej"
385 self.ui.warn(
385 self.ui.warn(
386 _("%d out of %d hunk%s FAILED -- saving rejects to file %s\n") %
386 _("%d out of %d hunk%s FAILED -- saving rejects to file %s\n") %
387 (len(self.rej), self.hunks, hunkstr, fname))
387 (len(self.rej), self.hunks, hunkstr, fname))
388 try: os.unlink(fname)
388 try: os.unlink(fname)
389 except:
389 except:
390 pass
390 pass
391 fp = file(fname, 'wb')
391 fp = file(fname, 'wb')
392 base = os.path.basename(self.fname)
392 base = os.path.basename(self.fname)
393 fp.write("--- %s\n+++ %s\n" % (base, base))
393 fp.write("--- %s\n+++ %s\n" % (base, base))
394 for x in self.rej:
394 for x in self.rej:
395 for l in x.hunk:
395 for l in x.hunk:
396 fp.write(l)
396 fp.write(l)
397 if l[-1] != '\n':
397 if l[-1] != '\n':
398 fp.write("\n\ No newline at end of file\n")
398 fp.write("\n\ No newline at end of file\n")
399
399
400 def write(self, dest=None):
400 def write(self, dest=None):
401 if self.dirty:
401 if self.dirty:
402 if not dest:
402 if not dest:
403 dest = self.fname
403 dest = self.fname
404 st = None
404 st = None
405 try:
405 try:
406 st = os.lstat(dest)
406 st = os.lstat(dest)
407 except OSError, inst:
407 except OSError, inst:
408 if inst.errno != errno.ENOENT:
408 if inst.errno != errno.ENOENT:
409 raise
409 raise
410 if st and st.st_nlink > 1:
410 if st and st.st_nlink > 1:
411 os.unlink(dest)
411 os.unlink(dest)
412 fp = file(dest, 'wb')
412 fp = file(dest, 'wb')
413 if st and st.st_nlink > 1:
413 if st and st.st_nlink > 1:
414 os.chmod(dest, st.st_mode)
414 os.chmod(dest, st.st_mode)
415 fp.writelines(self.lines)
415 fp.writelines(self.lines)
416 fp.close()
416 fp.close()
417
417
418 def close(self):
418 def close(self):
419 self.write()
419 self.write()
420 self.write_rej()
420 self.write_rej()
421
421
422 def apply(self, h, reverse):
422 def apply(self, h, reverse):
423 if not h.complete():
423 if not h.complete():
424 raise PatchError(_("bad hunk #%d %s (%d %d %d %d)") %
424 raise PatchError(_("bad hunk #%d %s (%d %d %d %d)") %
425 (h.number, h.desc, len(h.a), h.lena, len(h.b),
425 (h.number, h.desc, len(h.a), h.lena, len(h.b),
426 h.lenb))
426 h.lenb))
427
427
428 self.hunks += 1
428 self.hunks += 1
429 if reverse:
429 if reverse:
430 h.reverse()
430 h.reverse()
431
431
432 if self.missing:
432 if self.missing:
433 self.rej.append(h)
433 self.rej.append(h)
434 return -1
434 return -1
435
435
436 if self.exists and h.createfile():
436 if self.exists and h.createfile():
437 self.ui.warn(_("file %s already exists\n") % self.fname)
437 self.ui.warn(_("file %s already exists\n") % self.fname)
438 self.rej.append(h)
438 self.rej.append(h)
439 return -1
439 return -1
440
440
441 if isinstance(h, binhunk):
441 if isinstance(h, binhunk):
442 if h.rmfile():
442 if h.rmfile():
443 os.unlink(self.fname)
443 os.unlink(self.fname)
444 else:
444 else:
445 self.lines[:] = h.new()
445 self.lines[:] = h.new()
446 self.offset += len(h.new())
446 self.offset += len(h.new())
447 self.dirty = 1
447 self.dirty = 1
448 return 0
448 return 0
449
449
450 # fast case first, no offsets, no fuzz
450 # fast case first, no offsets, no fuzz
451 old = h.old()
451 old = h.old()
452 # patch starts counting at 1 unless we are adding the file
452 # patch starts counting at 1 unless we are adding the file
453 if h.starta == 0:
453 if h.starta == 0:
454 start = 0
454 start = 0
455 else:
455 else:
456 start = h.starta + self.offset - 1
456 start = h.starta + self.offset - 1
457 orig_start = start
457 orig_start = start
458 if diffhelpers.testhunk(old, self.lines, start) == 0:
458 if diffhelpers.testhunk(old, self.lines, start) == 0:
459 if h.rmfile():
459 if h.rmfile():
460 os.unlink(self.fname)
460 os.unlink(self.fname)
461 else:
461 else:
462 self.lines[start : start + h.lena] = h.new()
462 self.lines[start : start + h.lena] = h.new()
463 self.offset += h.lenb - h.lena
463 self.offset += h.lenb - h.lena
464 self.dirty = 1
464 self.dirty = 1
465 return 0
465 return 0
466
466
467 # ok, we couldn't match the hunk. Lets look for offsets and fuzz it
467 # ok, we couldn't match the hunk. Lets look for offsets and fuzz it
468 self.hashlines()
468 self.hashlines()
469 if h.hunk[-1][0] != ' ':
469 if h.hunk[-1][0] != ' ':
470 # if the hunk tried to put something at the bottom of the file
470 # if the hunk tried to put something at the bottom of the file
471 # override the start line and use eof here
471 # override the start line and use eof here
472 search_start = len(self.lines)
472 search_start = len(self.lines)
473 else:
473 else:
474 search_start = orig_start
474 search_start = orig_start
475
475
476 for fuzzlen in xrange(3):
476 for fuzzlen in xrange(3):
477 for toponly in [ True, False ]:
477 for toponly in [ True, False ]:
478 old = h.old(fuzzlen, toponly)
478 old = h.old(fuzzlen, toponly)
479
479
480 cand = self.findlines(old[0][1:], search_start)
480 cand = self.findlines(old[0][1:], search_start)
481 for l in cand:
481 for l in cand:
482 if diffhelpers.testhunk(old, self.lines, l) == 0:
482 if diffhelpers.testhunk(old, self.lines, l) == 0:
483 newlines = h.new(fuzzlen, toponly)
483 newlines = h.new(fuzzlen, toponly)
484 self.lines[l : l + len(old)] = newlines
484 self.lines[l : l + len(old)] = newlines
485 self.offset += len(newlines) - len(old)
485 self.offset += len(newlines) - len(old)
486 self.dirty = 1
486 self.dirty = 1
487 if fuzzlen:
487 if fuzzlen:
488 fuzzstr = "with fuzz %d " % fuzzlen
488 fuzzstr = "with fuzz %d " % fuzzlen
489 f = self.ui.warn
489 f = self.ui.warn
490 self.printfile(True)
490 self.printfile(True)
491 else:
491 else:
492 fuzzstr = ""
492 fuzzstr = ""
493 f = self.ui.note
493 f = self.ui.note
494 offset = l - orig_start - fuzzlen
494 offset = l - orig_start - fuzzlen
495 if offset == 1:
495 if offset == 1:
496 linestr = "line"
496 linestr = "line"
497 else:
497 else:
498 linestr = "lines"
498 linestr = "lines"
499 f(_("Hunk #%d succeeded at %d %s(offset %d %s).\n") %
499 f(_("Hunk #%d succeeded at %d %s(offset %d %s).\n") %
500 (h.number, l+1, fuzzstr, offset, linestr))
500 (h.number, l+1, fuzzstr, offset, linestr))
501 return fuzzlen
501 return fuzzlen
502 self.printfile(True)
502 self.printfile(True)
503 self.ui.warn(_("Hunk #%d FAILED at %d\n") % (h.number, orig_start))
503 self.ui.warn(_("Hunk #%d FAILED at %d\n") % (h.number, orig_start))
504 self.rej.append(h)
504 self.rej.append(h)
505 return -1
505 return -1
506
506
507 class hunk:
507 class hunk:
508 def __init__(self, desc, num, lr, context, gitpatch=None):
508 def __init__(self, desc, num, lr, context, gitpatch=None):
509 self.number = num
509 self.number = num
510 self.desc = desc
510 self.desc = desc
511 self.hunk = [ desc ]
511 self.hunk = [ desc ]
512 self.a = []
512 self.a = []
513 self.b = []
513 self.b = []
514 if context:
514 if context:
515 self.read_context_hunk(lr)
515 self.read_context_hunk(lr)
516 else:
516 else:
517 self.read_unified_hunk(lr)
517 self.read_unified_hunk(lr)
518 self.gitpatch = gitpatch
518 self.gitpatch = gitpatch
519
519
520 def read_unified_hunk(self, lr):
520 def read_unified_hunk(self, lr):
521 m = unidesc.match(self.desc)
521 m = unidesc.match(self.desc)
522 if not m:
522 if not m:
523 raise PatchError(_("bad hunk #%d") % self.number)
523 raise PatchError(_("bad hunk #%d") % self.number)
524 self.starta, foo, self.lena, self.startb, foo2, self.lenb = m.groups()
524 self.starta, foo, self.lena, self.startb, foo2, self.lenb = m.groups()
525 if self.lena == None:
525 if self.lena == None:
526 self.lena = 1
526 self.lena = 1
527 else:
527 else:
528 self.lena = int(self.lena)
528 self.lena = int(self.lena)
529 if self.lenb == None:
529 if self.lenb == None:
530 self.lenb = 1
530 self.lenb = 1
531 else:
531 else:
532 self.lenb = int(self.lenb)
532 self.lenb = int(self.lenb)
533 self.starta = int(self.starta)
533 self.starta = int(self.starta)
534 self.startb = int(self.startb)
534 self.startb = int(self.startb)
535 diffhelpers.addlines(lr.fp, self.hunk, self.lena, self.lenb, self.a, self.b)
535 diffhelpers.addlines(lr.fp, self.hunk, self.lena, self.lenb, self.a, self.b)
536 # if we hit eof before finishing out the hunk, the last line will
536 # if we hit eof before finishing out the hunk, the last line will
537 # be zero length. Lets try to fix it up.
537 # be zero length. Lets try to fix it up.
538 while len(self.hunk[-1]) == 0:
538 while len(self.hunk[-1]) == 0:
539 del self.hunk[-1]
539 del self.hunk[-1]
540 del self.a[-1]
540 del self.a[-1]
541 del self.b[-1]
541 del self.b[-1]
542 self.lena -= 1
542 self.lena -= 1
543 self.lenb -= 1
543 self.lenb -= 1
544
544
545 def read_context_hunk(self, lr):
545 def read_context_hunk(self, lr):
546 self.desc = lr.readline()
546 self.desc = lr.readline()
547 m = contextdesc.match(self.desc)
547 m = contextdesc.match(self.desc)
548 if not m:
548 if not m:
549 raise PatchError(_("bad hunk #%d") % self.number)
549 raise PatchError(_("bad hunk #%d") % self.number)
550 foo, self.starta, foo2, aend, foo3 = m.groups()
550 foo, self.starta, foo2, aend, foo3 = m.groups()
551 self.starta = int(self.starta)
551 self.starta = int(self.starta)
552 if aend == None:
552 if aend == None:
553 aend = self.starta
553 aend = self.starta
554 self.lena = int(aend) - self.starta
554 self.lena = int(aend) - self.starta
555 if self.starta:
555 if self.starta:
556 self.lena += 1
556 self.lena += 1
557 for x in xrange(self.lena):
557 for x in xrange(self.lena):
558 l = lr.readline()
558 l = lr.readline()
559 if l.startswith('---'):
559 if l.startswith('---'):
560 lr.push(l)
560 lr.push(l)
561 break
561 break
562 s = l[2:]
562 s = l[2:]
563 if l.startswith('- ') or l.startswith('! '):
563 if l.startswith('- ') or l.startswith('! '):
564 u = '-' + s
564 u = '-' + s
565 elif l.startswith(' '):
565 elif l.startswith(' '):
566 u = ' ' + s
566 u = ' ' + s
567 else:
567 else:
568 raise PatchError(_("bad hunk #%d old text line %d") %
568 raise PatchError(_("bad hunk #%d old text line %d") %
569 (self.number, x))
569 (self.number, x))
570 self.a.append(u)
570 self.a.append(u)
571 self.hunk.append(u)
571 self.hunk.append(u)
572
572
573 l = lr.readline()
573 l = lr.readline()
574 if l.startswith('\ '):
574 if l.startswith('\ '):
575 s = self.a[-1][:-1]
575 s = self.a[-1][:-1]
576 self.a[-1] = s
576 self.a[-1] = s
577 self.hunk[-1] = s
577 self.hunk[-1] = s
578 l = lr.readline()
578 l = lr.readline()
579 m = contextdesc.match(l)
579 m = contextdesc.match(l)
580 if not m:
580 if not m:
581 raise PatchError(_("bad hunk #%d") % self.number)
581 raise PatchError(_("bad hunk #%d") % self.number)
582 foo, self.startb, foo2, bend, foo3 = m.groups()
582 foo, self.startb, foo2, bend, foo3 = m.groups()
583 self.startb = int(self.startb)
583 self.startb = int(self.startb)
584 if bend == None:
584 if bend == None:
585 bend = self.startb
585 bend = self.startb
586 self.lenb = int(bend) - self.startb
586 self.lenb = int(bend) - self.startb
587 if self.startb:
587 if self.startb:
588 self.lenb += 1
588 self.lenb += 1
589 hunki = 1
589 hunki = 1
590 for x in xrange(self.lenb):
590 for x in xrange(self.lenb):
591 l = lr.readline()
591 l = lr.readline()
592 if l.startswith('\ '):
592 if l.startswith('\ '):
593 s = self.b[-1][:-1]
593 s = self.b[-1][:-1]
594 self.b[-1] = s
594 self.b[-1] = s
595 self.hunk[hunki-1] = s
595 self.hunk[hunki-1] = s
596 continue
596 continue
597 if not l:
597 if not l:
598 lr.push(l)
598 lr.push(l)
599 break
599 break
600 s = l[2:]
600 s = l[2:]
601 if l.startswith('+ ') or l.startswith('! '):
601 if l.startswith('+ ') or l.startswith('! '):
602 u = '+' + s
602 u = '+' + s
603 elif l.startswith(' '):
603 elif l.startswith(' '):
604 u = ' ' + s
604 u = ' ' + s
605 elif len(self.b) == 0:
605 elif len(self.b) == 0:
606 # this can happen when the hunk does not add any lines
606 # this can happen when the hunk does not add any lines
607 lr.push(l)
607 lr.push(l)
608 break
608 break
609 else:
609 else:
610 raise PatchError(_("bad hunk #%d old text line %d") %
610 raise PatchError(_("bad hunk #%d old text line %d") %
611 (self.number, x))
611 (self.number, x))
612 self.b.append(s)
612 self.b.append(s)
613 while True:
613 while True:
614 if hunki >= len(self.hunk):
614 if hunki >= len(self.hunk):
615 h = ""
615 h = ""
616 else:
616 else:
617 h = self.hunk[hunki]
617 h = self.hunk[hunki]
618 hunki += 1
618 hunki += 1
619 if h == u:
619 if h == u:
620 break
620 break
621 elif h.startswith('-'):
621 elif h.startswith('-'):
622 continue
622 continue
623 else:
623 else:
624 self.hunk.insert(hunki-1, u)
624 self.hunk.insert(hunki-1, u)
625 break
625 break
626
626
627 if not self.a:
627 if not self.a:
628 # this happens when lines were only added to the hunk
628 # this happens when lines were only added to the hunk
629 for x in self.hunk:
629 for x in self.hunk:
630 if x.startswith('-') or x.startswith(' '):
630 if x.startswith('-') or x.startswith(' '):
631 self.a.append(x)
631 self.a.append(x)
632 if not self.b:
632 if not self.b:
633 # this happens when lines were only deleted from the hunk
633 # this happens when lines were only deleted from the hunk
634 for x in self.hunk:
634 for x in self.hunk:
635 if x.startswith('+') or x.startswith(' '):
635 if x.startswith('+') or x.startswith(' '):
636 self.b.append(x[1:])
636 self.b.append(x[1:])
637 # @@ -start,len +start,len @@
637 # @@ -start,len +start,len @@
638 self.desc = "@@ -%d,%d +%d,%d @@\n" % (self.starta, self.lena,
638 self.desc = "@@ -%d,%d +%d,%d @@\n" % (self.starta, self.lena,
639 self.startb, self.lenb)
639 self.startb, self.lenb)
640 self.hunk[0] = self.desc
640 self.hunk[0] = self.desc
641
641
642 def reverse(self):
642 def reverse(self):
643 origlena = self.lena
643 origlena = self.lena
644 origstarta = self.starta
644 origstarta = self.starta
645 self.lena = self.lenb
645 self.lena = self.lenb
646 self.starta = self.startb
646 self.starta = self.startb
647 self.lenb = origlena
647 self.lenb = origlena
648 self.startb = origstarta
648 self.startb = origstarta
649 self.a = []
649 self.a = []
650 self.b = []
650 self.b = []
651 # self.hunk[0] is the @@ description
651 # self.hunk[0] is the @@ description
652 for x in xrange(1, len(self.hunk)):
652 for x in xrange(1, len(self.hunk)):
653 o = self.hunk[x]
653 o = self.hunk[x]
654 if o.startswith('-'):
654 if o.startswith('-'):
655 n = '+' + o[1:]
655 n = '+' + o[1:]
656 self.b.append(o[1:])
656 self.b.append(o[1:])
657 elif o.startswith('+'):
657 elif o.startswith('+'):
658 n = '-' + o[1:]
658 n = '-' + o[1:]
659 self.a.append(n)
659 self.a.append(n)
660 else:
660 else:
661 n = o
661 n = o
662 self.b.append(o[1:])
662 self.b.append(o[1:])
663 self.a.append(o)
663 self.a.append(o)
664 self.hunk[x] = o
664 self.hunk[x] = o
665
665
666 def fix_newline(self):
666 def fix_newline(self):
667 diffhelpers.fix_newline(self.hunk, self.a, self.b)
667 diffhelpers.fix_newline(self.hunk, self.a, self.b)
668
668
669 def complete(self):
669 def complete(self):
670 return len(self.a) == self.lena and len(self.b) == self.lenb
670 return len(self.a) == self.lena and len(self.b) == self.lenb
671
671
672 def createfile(self):
672 def createfile(self):
673 create = self.gitpatch is None or self.gitpatch.op == 'ADD'
673 create = self.gitpatch is None or self.gitpatch.op == 'ADD'
674 return self.starta == 0 and self.lena == 0 and create
674 return self.starta == 0 and self.lena == 0 and create
675
675
676 def rmfile(self):
676 def rmfile(self):
677 remove = self.gitpatch is None or self.gitpatch.op == 'DELETE'
677 remove = self.gitpatch is None or self.gitpatch.op == 'DELETE'
678 return self.startb == 0 and self.lenb == 0 and remove
678 return self.startb == 0 and self.lenb == 0 and remove
679
679
680 def fuzzit(self, l, fuzz, toponly):
680 def fuzzit(self, l, fuzz, toponly):
681 # this removes context lines from the top and bottom of list 'l'. It
681 # this removes context lines from the top and bottom of list 'l'. It
682 # checks the hunk to make sure only context lines are removed, and then
682 # checks the hunk to make sure only context lines are removed, and then
683 # returns a new shortened list of lines.
683 # returns a new shortened list of lines.
684 fuzz = min(fuzz, len(l)-1)
684 fuzz = min(fuzz, len(l)-1)
685 if fuzz:
685 if fuzz:
686 top = 0
686 top = 0
687 bot = 0
687 bot = 0
688 hlen = len(self.hunk)
688 hlen = len(self.hunk)
689 for x in xrange(hlen-1):
689 for x in xrange(hlen-1):
690 # the hunk starts with the @@ line, so use x+1
690 # the hunk starts with the @@ line, so use x+1
691 if self.hunk[x+1][0] == ' ':
691 if self.hunk[x+1][0] == ' ':
692 top += 1
692 top += 1
693 else:
693 else:
694 break
694 break
695 if not toponly:
695 if not toponly:
696 for x in xrange(hlen-1):
696 for x in xrange(hlen-1):
697 if self.hunk[hlen-bot-1][0] == ' ':
697 if self.hunk[hlen-bot-1][0] == ' ':
698 bot += 1
698 bot += 1
699 else:
699 else:
700 break
700 break
701
701
702 # top and bot now count context in the hunk
702 # top and bot now count context in the hunk
703 # adjust them if either one is short
703 # adjust them if either one is short
704 context = max(top, bot, 3)
704 context = max(top, bot, 3)
705 if bot < context:
705 if bot < context:
706 bot = max(0, fuzz - (context - bot))
706 bot = max(0, fuzz - (context - bot))
707 else:
707 else:
708 bot = min(fuzz, bot)
708 bot = min(fuzz, bot)
709 if top < context:
709 if top < context:
710 top = max(0, fuzz - (context - top))
710 top = max(0, fuzz - (context - top))
711 else:
711 else:
712 top = min(fuzz, top)
712 top = min(fuzz, top)
713
713
714 return l[top:len(l)-bot]
714 return l[top:len(l)-bot]
715 return l
715 return l
716
716
717 def old(self, fuzz=0, toponly=False):
717 def old(self, fuzz=0, toponly=False):
718 return self.fuzzit(self.a, fuzz, toponly)
718 return self.fuzzit(self.a, fuzz, toponly)
719
719
720 def newctrl(self):
720 def newctrl(self):
721 res = []
721 res = []
722 for x in self.hunk:
722 for x in self.hunk:
723 c = x[0]
723 c = x[0]
724 if c == ' ' or c == '+':
724 if c == ' ' or c == '+':
725 res.append(x)
725 res.append(x)
726 return res
726 return res
727
727
728 def new(self, fuzz=0, toponly=False):
728 def new(self, fuzz=0, toponly=False):
729 return self.fuzzit(self.b, fuzz, toponly)
729 return self.fuzzit(self.b, fuzz, toponly)
730
730
731 class binhunk:
731 class binhunk:
732 'A binary patch file. Only understands literals so far.'
732 'A binary patch file. Only understands literals so far.'
733 def __init__(self, gitpatch):
733 def __init__(self, gitpatch):
734 self.gitpatch = gitpatch
734 self.gitpatch = gitpatch
735 self.text = None
735 self.text = None
736 self.hunk = ['GIT binary patch\n']
736 self.hunk = ['GIT binary patch\n']
737
737
738 def createfile(self):
738 def createfile(self):
739 return self.gitpatch.op in ('ADD', 'RENAME', 'COPY')
739 return self.gitpatch.op in ('ADD', 'RENAME', 'COPY')
740
740
741 def rmfile(self):
741 def rmfile(self):
742 return self.gitpatch.op == 'DELETE'
742 return self.gitpatch.op == 'DELETE'
743
743
744 def complete(self):
744 def complete(self):
745 return self.text is not None
745 return self.text is not None
746
746
747 def new(self):
747 def new(self):
748 return [self.text]
748 return [self.text]
749
749
750 def extract(self, fp):
750 def extract(self, fp):
751 line = fp.readline()
751 line = fp.readline()
752 self.hunk.append(line)
752 self.hunk.append(line)
753 while line and not line.startswith('literal '):
753 while line and not line.startswith('literal '):
754 line = fp.readline()
754 line = fp.readline()
755 self.hunk.append(line)
755 self.hunk.append(line)
756 if not line:
756 if not line:
757 raise PatchError(_('could not extract binary patch'))
757 raise PatchError(_('could not extract binary patch'))
758 size = int(line[8:].rstrip())
758 size = int(line[8:].rstrip())
759 dec = []
759 dec = []
760 line = fp.readline()
760 line = fp.readline()
761 self.hunk.append(line)
761 self.hunk.append(line)
762 while len(line) > 1:
762 while len(line) > 1:
763 l = line[0]
763 l = line[0]
764 if l <= 'Z' and l >= 'A':
764 if l <= 'Z' and l >= 'A':
765 l = ord(l) - ord('A') + 1
765 l = ord(l) - ord('A') + 1
766 else:
766 else:
767 l = ord(l) - ord('a') + 27
767 l = ord(l) - ord('a') + 27
768 dec.append(base85.b85decode(line[1:-1])[:l])
768 dec.append(base85.b85decode(line[1:-1])[:l])
769 line = fp.readline()
769 line = fp.readline()
770 self.hunk.append(line)
770 self.hunk.append(line)
771 text = zlib.decompress(''.join(dec))
771 text = zlib.decompress(''.join(dec))
772 if len(text) != size:
772 if len(text) != size:
773 raise PatchError(_('binary patch is %d bytes, not %d') %
773 raise PatchError(_('binary patch is %d bytes, not %d') %
774 len(text), size)
774 len(text), size)
775 self.text = text
775 self.text = text
776
776
777 def parsefilename(str):
777 def parsefilename(str):
778 # --- filename \t|space stuff
778 # --- filename \t|space stuff
779 s = str[4:].rstrip('\r\n')
779 s = str[4:].rstrip('\r\n')
780 i = s.find('\t')
780 i = s.find('\t')
781 if i < 0:
781 if i < 0:
782 i = s.find(' ')
782 i = s.find(' ')
783 if i < 0:
783 if i < 0:
784 return s
784 return s
785 return s[:i]
785 return s[:i]
786
786
787 def selectfile(afile_orig, bfile_orig, hunk, strip, reverse):
787 def selectfile(afile_orig, bfile_orig, hunk, strip, reverse):
788 def pathstrip(path, count=1):
788 def pathstrip(path, count=1):
789 pathlen = len(path)
789 pathlen = len(path)
790 i = 0
790 i = 0
791 if count == 0:
791 if count == 0:
792 return path.rstrip()
792 return path.rstrip()
793 while count > 0:
793 while count > 0:
794 i = path.find('/', i)
794 i = path.find('/', i)
795 if i == -1:
795 if i == -1:
796 raise PatchError(_("unable to strip away %d dirs from %s") %
796 raise PatchError(_("unable to strip away %d dirs from %s") %
797 (count, path))
797 (count, path))
798 i += 1
798 i += 1
799 # consume '//' in the path
799 # consume '//' in the path
800 while i < pathlen - 1 and path[i] == '/':
800 while i < pathlen - 1 and path[i] == '/':
801 i += 1
801 i += 1
802 count -= 1
802 count -= 1
803 return path[i:].rstrip()
803 return path[i:].rstrip()
804
804
805 nulla = afile_orig == "/dev/null"
805 nulla = afile_orig == "/dev/null"
806 nullb = bfile_orig == "/dev/null"
806 nullb = bfile_orig == "/dev/null"
807 afile = pathstrip(afile_orig, strip)
807 afile = pathstrip(afile_orig, strip)
808 gooda = not nulla and os.path.exists(afile)
808 gooda = not nulla and os.path.exists(afile)
809 bfile = pathstrip(bfile_orig, strip)
809 bfile = pathstrip(bfile_orig, strip)
810 if afile == bfile:
810 if afile == bfile:
811 goodb = gooda
811 goodb = gooda
812 else:
812 else:
813 goodb = not nullb and os.path.exists(bfile)
813 goodb = not nullb and os.path.exists(bfile)
814 createfunc = hunk.createfile
814 createfunc = hunk.createfile
815 if reverse:
815 if reverse:
816 createfunc = hunk.rmfile
816 createfunc = hunk.rmfile
817 missing = not goodb and not gooda and not createfunc()
817 missing = not goodb and not gooda and not createfunc()
818 fname = None
818 fname = None
819 if not missing:
819 if not missing:
820 if gooda and goodb:
820 if gooda and goodb:
821 fname = (afile in bfile) and afile or bfile
821 fname = (afile in bfile) and afile or bfile
822 elif gooda:
822 elif gooda:
823 fname = afile
823 fname = afile
824
824
825 if not fname:
825 if not fname:
826 if not nullb:
826 if not nullb:
827 fname = (afile in bfile) and afile or bfile
827 fname = (afile in bfile) and afile or bfile
828 elif not nulla:
828 elif not nulla:
829 fname = afile
829 fname = afile
830 else:
830 else:
831 raise PatchError(_("undefined source and destination files"))
831 raise PatchError(_("undefined source and destination files"))
832
832
833 return fname, missing
833 return fname, missing
834
834
835 class linereader:
835 class linereader:
836 # simple class to allow pushing lines back into the input stream
836 # simple class to allow pushing lines back into the input stream
837 def __init__(self, fp):
837 def __init__(self, fp):
838 self.fp = fp
838 self.fp = fp
839 self.buf = []
839 self.buf = []
840
840
841 def push(self, line):
841 def push(self, line):
842 self.buf.append(line)
842 self.buf.append(line)
843
843
844 def readline(self):
844 def readline(self):
845 if self.buf:
845 if self.buf:
846 l = self.buf[0]
846 l = self.buf[0]
847 del self.buf[0]
847 del self.buf[0]
848 return l
848 return l
849 return self.fp.readline()
849 return self.fp.readline()
850
850
851 def iterhunks(ui, fp, sourcefile=None):
851 def iterhunks(ui, fp, sourcefile=None):
852 """Read a patch and yield the following events:
852 """Read a patch and yield the following events:
853 - ("file", afile, bfile, firsthunk): select a new target file.
853 - ("file", afile, bfile, firsthunk): select a new target file.
854 - ("hunk", hunk): a new hunk is ready to be applied, follows a
854 - ("hunk", hunk): a new hunk is ready to be applied, follows a
855 "file" event.
855 "file" event.
856 - ("git", gitchanges): current diff is in git format, gitchanges
856 - ("git", gitchanges): current diff is in git format, gitchanges
857 maps filenames to gitpatch records. Unique event.
857 maps filenames to gitpatch records. Unique event.
858 """
858 """
859
859
860 def scangitpatch(fp, firstline):
860 def scangitpatch(fp, firstline):
861 '''git patches can modify a file, then copy that file to
861 '''git patches can modify a file, then copy that file to
862 a new file, but expect the source to be the unmodified form.
862 a new file, but expect the source to be the unmodified form.
863 So we scan the patch looking for that case so we can do
863 So we scan the patch looking for that case so we can do
864 the copies ahead of time.'''
864 the copies ahead of time.'''
865
865
866 pos = 0
866 pos = 0
867 try:
867 try:
868 pos = fp.tell()
868 pos = fp.tell()
869 except IOError:
869 except IOError:
870 fp = cStringIO.StringIO(fp.read())
870 fp = cStringIO.StringIO(fp.read())
871
871
872 (dopatch, gitpatches) = readgitpatch(fp, firstline)
872 (dopatch, gitpatches) = readgitpatch(fp, firstline)
873 fp.seek(pos)
873 fp.seek(pos)
874
874
875 return fp, dopatch, gitpatches
875 return fp, dopatch, gitpatches
876
876
877 changed = {}
877 changed = {}
878 current_hunk = None
878 current_hunk = None
879 afile = ""
879 afile = ""
880 bfile = ""
880 bfile = ""
881 state = None
881 state = None
882 hunknum = 0
882 hunknum = 0
883 emitfile = False
883 emitfile = False
884
884
885 git = False
885 git = False
886 gitre = re.compile('diff --git (a/.*) (b/.*)')
886 gitre = re.compile('diff --git (a/.*) (b/.*)')
887
887
888 # our states
888 # our states
889 BFILE = 1
889 BFILE = 1
890 context = None
890 context = None
891 lr = linereader(fp)
891 lr = linereader(fp)
892 dopatch = True
892 dopatch = True
893 # gitworkdone is True if a git operation (copy, rename, ...) was
894 # performed already for the current file. Useful when the file
895 # section may have no hunk.
893 gitworkdone = False
896 gitworkdone = False
894
897
895 while True:
898 while True:
896 newfile = False
899 newfile = False
897 x = lr.readline()
900 x = lr.readline()
898 if not x:
901 if not x:
899 break
902 break
900 if current_hunk:
903 if current_hunk:
901 if x.startswith('\ '):
904 if x.startswith('\ '):
902 current_hunk.fix_newline()
905 current_hunk.fix_newline()
903 yield 'hunk', current_hunk
906 yield 'hunk', current_hunk
904 current_hunk = None
907 current_hunk = None
905 gitworkdone = False
908 gitworkdone = False
906 if ((sourcefile or state == BFILE) and ((not context and x[0] == '@') or
909 if ((sourcefile or state == BFILE) and ((not context and x[0] == '@') or
907 ((context or context == None) and x.startswith('***************')))):
910 ((context or context == None) and x.startswith('***************')))):
908 try:
911 try:
909 if context == None and x.startswith('***************'):
912 if context == None and x.startswith('***************'):
910 context = True
913 context = True
911 gpatch = changed.get(bfile[2:], (None, None))[1]
914 gpatch = changed.get(bfile[2:], (None, None))[1]
912 current_hunk = hunk(x, hunknum + 1, lr, context, gpatch)
915 current_hunk = hunk(x, hunknum + 1, lr, context, gpatch)
913 except PatchError, err:
916 except PatchError, err:
914 ui.debug(err)
917 ui.debug(err)
915 current_hunk = None
918 current_hunk = None
916 continue
919 continue
917 hunknum += 1
920 hunknum += 1
918 if emitfile:
921 if emitfile:
919 emitfile = False
922 emitfile = False
920 yield 'file', (afile, bfile, current_hunk)
923 yield 'file', (afile, bfile, current_hunk)
921 elif state == BFILE and x.startswith('GIT binary patch'):
924 elif state == BFILE and x.startswith('GIT binary patch'):
922 current_hunk = binhunk(changed[bfile[2:]][1])
925 current_hunk = binhunk(changed[bfile[2:]][1])
923 hunknum += 1
926 hunknum += 1
924 if emitfile:
927 if emitfile:
925 emitfile = False
928 emitfile = False
926 yield 'file', (afile, bfile, current_hunk)
929 yield 'file', (afile, bfile, current_hunk)
927 current_hunk.extract(fp)
930 current_hunk.extract(fp)
928 elif x.startswith('diff --git'):
931 elif x.startswith('diff --git'):
929 # check for git diff, scanning the whole patch file if needed
932 # check for git diff, scanning the whole patch file if needed
930 m = gitre.match(x)
933 m = gitre.match(x)
931 if m:
934 if m:
932 afile, bfile = m.group(1, 2)
935 afile, bfile = m.group(1, 2)
933 if not git:
936 if not git:
934 git = True
937 git = True
935 fp, dopatch, gitpatches = scangitpatch(fp, x)
938 fp, dopatch, gitpatches = scangitpatch(fp, x)
936 yield 'git', gitpatches
939 yield 'git', gitpatches
937 for gp in gitpatches:
940 for gp in gitpatches:
938 changed[gp.path] = (gp.op, gp)
941 changed[gp.path] = (gp.op, gp)
939 # else error?
942 # else error?
940 # copy/rename + modify should modify target, not source
943 # copy/rename + modify should modify target, not source
941 if changed.get(bfile[2:], (None, None))[0] in ('COPY',
944 gitop = changed.get(bfile[2:], (None, None))[0]
942 'RENAME'):
945 if gitop in ('COPY', 'DELETE', 'RENAME'):
943 afile = bfile
946 afile = bfile
944 gitworkdone = True
947 gitworkdone = True
945 newfile = True
948 newfile = True
946 elif x.startswith('---'):
949 elif x.startswith('---'):
947 # check for a unified diff
950 # check for a unified diff
948 l2 = lr.readline()
951 l2 = lr.readline()
949 if not l2.startswith('+++'):
952 if not l2.startswith('+++'):
950 lr.push(l2)
953 lr.push(l2)
951 continue
954 continue
952 newfile = True
955 newfile = True
953 context = False
956 context = False
954 afile = parsefilename(x)
957 afile = parsefilename(x)
955 bfile = parsefilename(l2)
958 bfile = parsefilename(l2)
956 elif x.startswith('***'):
959 elif x.startswith('***'):
957 # check for a context diff
960 # check for a context diff
958 l2 = lr.readline()
961 l2 = lr.readline()
959 if not l2.startswith('---'):
962 if not l2.startswith('---'):
960 lr.push(l2)
963 lr.push(l2)
961 continue
964 continue
962 l3 = lr.readline()
965 l3 = lr.readline()
963 lr.push(l3)
966 lr.push(l3)
964 if not l3.startswith("***************"):
967 if not l3.startswith("***************"):
965 lr.push(l2)
968 lr.push(l2)
966 continue
969 continue
967 newfile = True
970 newfile = True
968 context = True
971 context = True
969 afile = parsefilename(x)
972 afile = parsefilename(x)
970 bfile = parsefilename(l2)
973 bfile = parsefilename(l2)
971
974
972 if newfile:
975 if newfile:
973 emitfile = True
976 emitfile = True
974 state = BFILE
977 state = BFILE
975 hunknum = 0
978 hunknum = 0
976 if current_hunk:
979 if current_hunk:
977 if current_hunk.complete():
980 if current_hunk.complete():
978 yield 'hunk', current_hunk
981 yield 'hunk', current_hunk
979 else:
982 else:
980 raise PatchError(_("malformed patch %s %s") % (afile,
983 raise PatchError(_("malformed patch %s %s") % (afile,
981 current_hunk.desc))
984 current_hunk.desc))
982
985
983 if hunknum == 0 and dopatch and not gitworkdone:
986 if hunknum == 0 and dopatch and not gitworkdone:
984 raise NoHunks
987 raise NoHunks
985
988
986 def applydiff(ui, fp, changed, strip=1, sourcefile=None, reverse=False,
989 def applydiff(ui, fp, changed, strip=1, sourcefile=None, reverse=False,
987 rejmerge=None, updatedir=None):
990 rejmerge=None, updatedir=None):
988 """reads a patch from fp and tries to apply it. The dict 'changed' is
991 """reads a patch from fp and tries to apply it. The dict 'changed' is
989 filled in with all of the filenames changed by the patch. Returns 0
992 filled in with all of the filenames changed by the patch. Returns 0
990 for a clean patch, -1 if any rejects were found and 1 if there was
993 for a clean patch, -1 if any rejects were found and 1 if there was
991 any fuzz."""
994 any fuzz."""
992
995
993 rejects = 0
996 rejects = 0
994 err = 0
997 err = 0
995 current_file = None
998 current_file = None
996 gitpatches = None
999 gitpatches = None
997
1000
998 def closefile():
1001 def closefile():
999 if not current_file:
1002 if not current_file:
1000 return 0
1003 return 0
1001 current_file.close()
1004 current_file.close()
1002 if rejmerge:
1005 if rejmerge:
1003 rejmerge(current_file)
1006 rejmerge(current_file)
1004 return len(current_file.rej)
1007 return len(current_file.rej)
1005
1008
1006 for state, values in iterhunks(ui, fp, sourcefile):
1009 for state, values in iterhunks(ui, fp, sourcefile):
1007 if state == 'hunk':
1010 if state == 'hunk':
1008 if not current_file:
1011 if not current_file:
1009 continue
1012 continue
1010 current_hunk = values
1013 current_hunk = values
1011 ret = current_file.apply(current_hunk, reverse)
1014 ret = current_file.apply(current_hunk, reverse)
1012 if ret >= 0:
1015 if ret >= 0:
1013 changed.setdefault(current_file.fname, (None, None))
1016 changed.setdefault(current_file.fname, (None, None))
1014 if ret > 0:
1017 if ret > 0:
1015 err = 1
1018 err = 1
1016 elif state == 'file':
1019 elif state == 'file':
1017 rejects += closefile()
1020 rejects += closefile()
1018 afile, bfile, first_hunk = values
1021 afile, bfile, first_hunk = values
1019 try:
1022 try:
1020 if sourcefile:
1023 if sourcefile:
1021 current_file = patchfile(ui, sourcefile)
1024 current_file = patchfile(ui, sourcefile)
1022 else:
1025 else:
1023 current_file, missing = selectfile(afile, bfile, first_hunk,
1026 current_file, missing = selectfile(afile, bfile, first_hunk,
1024 strip, reverse)
1027 strip, reverse)
1025 current_file = patchfile(ui, current_file, missing)
1028 current_file = patchfile(ui, current_file, missing)
1026 except PatchError, err:
1029 except PatchError, err:
1027 ui.warn(str(err) + '\n')
1030 ui.warn(str(err) + '\n')
1028 current_file, current_hunk = None, None
1031 current_file, current_hunk = None, None
1029 rejects += 1
1032 rejects += 1
1030 continue
1033 continue
1031 elif state == 'git':
1034 elif state == 'git':
1032 gitpatches = values
1035 gitpatches = values
1033 for gp in gitpatches:
1036 for gp in gitpatches:
1034 if gp.op in ('COPY', 'RENAME'):
1037 if gp.op in ('COPY', 'RENAME'):
1035 copyfile(gp.oldpath, gp.path)
1038 copyfile(gp.oldpath, gp.path)
1036 changed[gp.path] = (gp.op, gp)
1039 changed[gp.path] = (gp.op, gp)
1037 else:
1040 else:
1038 raise util.Abort(_('unsupported parser state: %s') % state)
1041 raise util.Abort(_('unsupported parser state: %s') % state)
1039
1042
1040 rejects += closefile()
1043 rejects += closefile()
1041
1044
1042 if updatedir and gitpatches:
1045 if updatedir and gitpatches:
1043 updatedir(gitpatches)
1046 updatedir(gitpatches)
1044 if rejects:
1047 if rejects:
1045 return -1
1048 return -1
1046 return err
1049 return err
1047
1050
1048 def diffopts(ui, opts={}, untrusted=False):
1051 def diffopts(ui, opts={}, untrusted=False):
1049 def get(key, name=None):
1052 def get(key, name=None):
1050 return (opts.get(key) or
1053 return (opts.get(key) or
1051 ui.configbool('diff', name or key, None, untrusted=untrusted))
1054 ui.configbool('diff', name or key, None, untrusted=untrusted))
1052 return mdiff.diffopts(
1055 return mdiff.diffopts(
1053 text=opts.get('text'),
1056 text=opts.get('text'),
1054 git=get('git'),
1057 git=get('git'),
1055 nodates=get('nodates'),
1058 nodates=get('nodates'),
1056 showfunc=get('show_function', 'showfunc'),
1059 showfunc=get('show_function', 'showfunc'),
1057 ignorews=get('ignore_all_space', 'ignorews'),
1060 ignorews=get('ignore_all_space', 'ignorews'),
1058 ignorewsamount=get('ignore_space_change', 'ignorewsamount'),
1061 ignorewsamount=get('ignore_space_change', 'ignorewsamount'),
1059 ignoreblanklines=get('ignore_blank_lines', 'ignoreblanklines'),
1062 ignoreblanklines=get('ignore_blank_lines', 'ignoreblanklines'),
1060 context=get('unified'))
1063 context=get('unified'))
1061
1064
1062 def updatedir(ui, repo, patches):
1065 def updatedir(ui, repo, patches):
1063 '''Update dirstate after patch application according to metadata'''
1066 '''Update dirstate after patch application according to metadata'''
1064 if not patches:
1067 if not patches:
1065 return
1068 return
1066 copies = []
1069 copies = []
1067 removes = {}
1070 removes = {}
1068 cfiles = patches.keys()
1071 cfiles = patches.keys()
1069 cwd = repo.getcwd()
1072 cwd = repo.getcwd()
1070 if cwd:
1073 if cwd:
1071 cfiles = [util.pathto(repo.root, cwd, f) for f in patches.keys()]
1074 cfiles = [util.pathto(repo.root, cwd, f) for f in patches.keys()]
1072 for f in patches:
1075 for f in patches:
1073 ctype, gp = patches[f]
1076 ctype, gp = patches[f]
1074 if ctype == 'RENAME':
1077 if ctype == 'RENAME':
1075 copies.append((gp.oldpath, gp.path))
1078 copies.append((gp.oldpath, gp.path))
1076 removes[gp.oldpath] = 1
1079 removes[gp.oldpath] = 1
1077 elif ctype == 'COPY':
1080 elif ctype == 'COPY':
1078 copies.append((gp.oldpath, gp.path))
1081 copies.append((gp.oldpath, gp.path))
1079 elif ctype == 'DELETE':
1082 elif ctype == 'DELETE':
1080 removes[gp.path] = 1
1083 removes[gp.path] = 1
1081 for src, dst in copies:
1084 for src, dst in copies:
1082 repo.copy(src, dst)
1085 repo.copy(src, dst)
1083 removes = removes.keys()
1086 removes = removes.keys()
1084 if removes:
1087 if removes:
1085 removes.sort()
1088 removes.sort()
1086 repo.remove(removes, True)
1089 repo.remove(removes, True)
1087 for f in patches:
1090 for f in patches:
1088 ctype, gp = patches[f]
1091 ctype, gp = patches[f]
1089 if gp and gp.mode:
1092 if gp and gp.mode:
1090 flags = ''
1093 flags = ''
1091 if gp.mode & 0100:
1094 if gp.mode & 0100:
1092 flags = 'x'
1095 flags = 'x'
1093 elif gp.mode & 020000:
1096 elif gp.mode & 020000:
1094 flags = 'l'
1097 flags = 'l'
1095 dst = os.path.join(repo.root, gp.path)
1098 dst = os.path.join(repo.root, gp.path)
1096 # patch won't create empty files
1099 # patch won't create empty files
1097 if ctype == 'ADD' and not os.path.exists(dst):
1100 if ctype == 'ADD' and not os.path.exists(dst):
1098 repo.wwrite(gp.path, '', flags)
1101 repo.wwrite(gp.path, '', flags)
1099 else:
1102 else:
1100 util.set_flags(dst, flags)
1103 util.set_flags(dst, flags)
1101 cmdutil.addremove(repo, cfiles)
1104 cmdutil.addremove(repo, cfiles)
1102 files = patches.keys()
1105 files = patches.keys()
1103 files.extend([r for r in removes if r not in files])
1106 files.extend([r for r in removes if r not in files])
1104 files.sort()
1107 files.sort()
1105
1108
1106 return files
1109 return files
1107
1110
1108 def b85diff(to, tn):
1111 def b85diff(to, tn):
1109 '''print base85-encoded binary diff'''
1112 '''print base85-encoded binary diff'''
1110 def gitindex(text):
1113 def gitindex(text):
1111 if not text:
1114 if not text:
1112 return '0' * 40
1115 return '0' * 40
1113 l = len(text)
1116 l = len(text)
1114 s = sha.new('blob %d\0' % l)
1117 s = sha.new('blob %d\0' % l)
1115 s.update(text)
1118 s.update(text)
1116 return s.hexdigest()
1119 return s.hexdigest()
1117
1120
1118 def fmtline(line):
1121 def fmtline(line):
1119 l = len(line)
1122 l = len(line)
1120 if l <= 26:
1123 if l <= 26:
1121 l = chr(ord('A') + l - 1)
1124 l = chr(ord('A') + l - 1)
1122 else:
1125 else:
1123 l = chr(l - 26 + ord('a') - 1)
1126 l = chr(l - 26 + ord('a') - 1)
1124 return '%c%s\n' % (l, base85.b85encode(line, True))
1127 return '%c%s\n' % (l, base85.b85encode(line, True))
1125
1128
1126 def chunk(text, csize=52):
1129 def chunk(text, csize=52):
1127 l = len(text)
1130 l = len(text)
1128 i = 0
1131 i = 0
1129 while i < l:
1132 while i < l:
1130 yield text[i:i+csize]
1133 yield text[i:i+csize]
1131 i += csize
1134 i += csize
1132
1135
1133 tohash = gitindex(to)
1136 tohash = gitindex(to)
1134 tnhash = gitindex(tn)
1137 tnhash = gitindex(tn)
1135 if tohash == tnhash:
1138 if tohash == tnhash:
1136 return ""
1139 return ""
1137
1140
1138 # TODO: deltas
1141 # TODO: deltas
1139 ret = ['index %s..%s\nGIT binary patch\nliteral %s\n' %
1142 ret = ['index %s..%s\nGIT binary patch\nliteral %s\n' %
1140 (tohash, tnhash, len(tn))]
1143 (tohash, tnhash, len(tn))]
1141 for l in chunk(zlib.compress(tn)):
1144 for l in chunk(zlib.compress(tn)):
1142 ret.append(fmtline(l))
1145 ret.append(fmtline(l))
1143 ret.append('\n')
1146 ret.append('\n')
1144 return ''.join(ret)
1147 return ''.join(ret)
1145
1148
1146 def diff(repo, node1=None, node2=None, files=None, match=util.always,
1149 def diff(repo, node1=None, node2=None, files=None, match=util.always,
1147 fp=None, changes=None, opts=None):
1150 fp=None, changes=None, opts=None):
1148 '''print diff of changes to files between two nodes, or node and
1151 '''print diff of changes to files between two nodes, or node and
1149 working directory.
1152 working directory.
1150
1153
1151 if node1 is None, use first dirstate parent instead.
1154 if node1 is None, use first dirstate parent instead.
1152 if node2 is None, compare node1 with working directory.'''
1155 if node2 is None, compare node1 with working directory.'''
1153
1156
1154 if opts is None:
1157 if opts is None:
1155 opts = mdiff.defaultopts
1158 opts = mdiff.defaultopts
1156 if fp is None:
1159 if fp is None:
1157 fp = repo.ui
1160 fp = repo.ui
1158
1161
1159 if not node1:
1162 if not node1:
1160 node1 = repo.dirstate.parents()[0]
1163 node1 = repo.dirstate.parents()[0]
1161
1164
1162 ccache = {}
1165 ccache = {}
1163 def getctx(r):
1166 def getctx(r):
1164 if r not in ccache:
1167 if r not in ccache:
1165 ccache[r] = context.changectx(repo, r)
1168 ccache[r] = context.changectx(repo, r)
1166 return ccache[r]
1169 return ccache[r]
1167
1170
1168 flcache = {}
1171 flcache = {}
1169 def getfilectx(f, ctx):
1172 def getfilectx(f, ctx):
1170 flctx = ctx.filectx(f, filelog=flcache.get(f))
1173 flctx = ctx.filectx(f, filelog=flcache.get(f))
1171 if f not in flcache:
1174 if f not in flcache:
1172 flcache[f] = flctx._filelog
1175 flcache[f] = flctx._filelog
1173 return flctx
1176 return flctx
1174
1177
1175 # reading the data for node1 early allows it to play nicely
1178 # reading the data for node1 early allows it to play nicely
1176 # with repo.status and the revlog cache.
1179 # with repo.status and the revlog cache.
1177 ctx1 = context.changectx(repo, node1)
1180 ctx1 = context.changectx(repo, node1)
1178 # force manifest reading
1181 # force manifest reading
1179 man1 = ctx1.manifest()
1182 man1 = ctx1.manifest()
1180 date1 = util.datestr(ctx1.date())
1183 date1 = util.datestr(ctx1.date())
1181
1184
1182 if not changes:
1185 if not changes:
1183 changes = repo.status(node1, node2, files, match=match)[:5]
1186 changes = repo.status(node1, node2, files, match=match)[:5]
1184 modified, added, removed, deleted, unknown = changes
1187 modified, added, removed, deleted, unknown = changes
1185
1188
1186 if not modified and not added and not removed:
1189 if not modified and not added and not removed:
1187 return
1190 return
1188
1191
1189 if node2:
1192 if node2:
1190 ctx2 = context.changectx(repo, node2)
1193 ctx2 = context.changectx(repo, node2)
1191 execf2 = ctx2.manifest().execf
1194 execf2 = ctx2.manifest().execf
1192 linkf2 = ctx2.manifest().linkf
1195 linkf2 = ctx2.manifest().linkf
1193 else:
1196 else:
1194 ctx2 = context.workingctx(repo)
1197 ctx2 = context.workingctx(repo)
1195 execf2 = util.execfunc(repo.root, None)
1198 execf2 = util.execfunc(repo.root, None)
1196 linkf2 = util.linkfunc(repo.root, None)
1199 linkf2 = util.linkfunc(repo.root, None)
1197 if execf2 is None:
1200 if execf2 is None:
1198 mc = ctx2.parents()[0].manifest().copy()
1201 mc = ctx2.parents()[0].manifest().copy()
1199 execf2 = mc.execf
1202 execf2 = mc.execf
1200 linkf2 = mc.linkf
1203 linkf2 = mc.linkf
1201
1204
1202 # returns False if there was no rename between ctx1 and ctx2
1205 # returns False if there was no rename between ctx1 and ctx2
1203 # returns None if the file was created between ctx1 and ctx2
1206 # returns None if the file was created between ctx1 and ctx2
1204 # returns the (file, node) present in ctx1 that was renamed to f in ctx2
1207 # returns the (file, node) present in ctx1 that was renamed to f in ctx2
1205 # This will only really work if c1 is the Nth 1st parent of c2.
1208 # This will only really work if c1 is the Nth 1st parent of c2.
1206 def renamed(c1, c2, man, f):
1209 def renamed(c1, c2, man, f):
1207 startrev = c1.rev()
1210 startrev = c1.rev()
1208 c = c2
1211 c = c2
1209 crev = c.rev()
1212 crev = c.rev()
1210 if crev is None:
1213 if crev is None:
1211 crev = repo.changelog.count()
1214 crev = repo.changelog.count()
1212 orig = f
1215 orig = f
1213 files = (f,)
1216 files = (f,)
1214 while crev > startrev:
1217 while crev > startrev:
1215 if f in files:
1218 if f in files:
1216 try:
1219 try:
1217 src = getfilectx(f, c).renamed()
1220 src = getfilectx(f, c).renamed()
1218 except revlog.LookupError:
1221 except revlog.LookupError:
1219 return None
1222 return None
1220 if src:
1223 if src:
1221 f = src[0]
1224 f = src[0]
1222 crev = c.parents()[0].rev()
1225 crev = c.parents()[0].rev()
1223 # try to reuse
1226 # try to reuse
1224 c = getctx(crev)
1227 c = getctx(crev)
1225 files = c.files()
1228 files = c.files()
1226 if f not in man:
1229 if f not in man:
1227 return None
1230 return None
1228 if f == orig:
1231 if f == orig:
1229 return False
1232 return False
1230 return f
1233 return f
1231
1234
1232 if repo.ui.quiet:
1235 if repo.ui.quiet:
1233 r = None
1236 r = None
1234 else:
1237 else:
1235 hexfunc = repo.ui.debugflag and hex or short
1238 hexfunc = repo.ui.debugflag and hex or short
1236 r = [hexfunc(node) for node in [node1, node2] if node]
1239 r = [hexfunc(node) for node in [node1, node2] if node]
1237
1240
1238 if opts.git:
1241 if opts.git:
1239 copied = {}
1242 copied = {}
1240 c1, c2 = ctx1, ctx2
1243 c1, c2 = ctx1, ctx2
1241 files = added
1244 files = added
1242 man = man1
1245 man = man1
1243 if node2 and ctx1.rev() >= ctx2.rev():
1246 if node2 and ctx1.rev() >= ctx2.rev():
1244 # renamed() starts at c2 and walks back in history until c1.
1247 # renamed() starts at c2 and walks back in history until c1.
1245 # Since ctx1.rev() >= ctx2.rev(), invert ctx2 and ctx1 to
1248 # Since ctx1.rev() >= ctx2.rev(), invert ctx2 and ctx1 to
1246 # detect (inverted) copies.
1249 # detect (inverted) copies.
1247 c1, c2 = ctx2, ctx1
1250 c1, c2 = ctx2, ctx1
1248 files = removed
1251 files = removed
1249 man = ctx2.manifest()
1252 man = ctx2.manifest()
1250 for f in files:
1253 for f in files:
1251 src = renamed(c1, c2, man, f)
1254 src = renamed(c1, c2, man, f)
1252 if src:
1255 if src:
1253 copied[f] = src
1256 copied[f] = src
1254 if ctx1 == c2:
1257 if ctx1 == c2:
1255 # invert the copied dict
1258 # invert the copied dict
1256 copied = dict([(v, k) for (k, v) in copied.iteritems()])
1259 copied = dict([(v, k) for (k, v) in copied.iteritems()])
1257 # If we've renamed file foo to bar (copied['bar'] = 'foo'),
1260 # If we've renamed file foo to bar (copied['bar'] = 'foo'),
1258 # avoid showing a diff for foo if we're going to show
1261 # avoid showing a diff for foo if we're going to show
1259 # the rename to bar.
1262 # the rename to bar.
1260 srcs = [x[1] for x in copied.iteritems() if x[0] in added]
1263 srcs = [x[1] for x in copied.iteritems() if x[0] in added]
1261
1264
1262 all = modified + added + removed
1265 all = modified + added + removed
1263 all.sort()
1266 all.sort()
1264 gone = {}
1267 gone = {}
1265
1268
1266 for f in all:
1269 for f in all:
1267 to = None
1270 to = None
1268 tn = None
1271 tn = None
1269 dodiff = True
1272 dodiff = True
1270 header = []
1273 header = []
1271 if f in man1:
1274 if f in man1:
1272 to = getfilectx(f, ctx1).data()
1275 to = getfilectx(f, ctx1).data()
1273 if f not in removed:
1276 if f not in removed:
1274 tn = getfilectx(f, ctx2).data()
1277 tn = getfilectx(f, ctx2).data()
1275 a, b = f, f
1278 a, b = f, f
1276 if opts.git:
1279 if opts.git:
1277 def gitmode(x, l):
1280 def gitmode(x, l):
1278 return l and '120000' or (x and '100755' or '100644')
1281 return l and '120000' or (x and '100755' or '100644')
1279 def addmodehdr(header, omode, nmode):
1282 def addmodehdr(header, omode, nmode):
1280 if omode != nmode:
1283 if omode != nmode:
1281 header.append('old mode %s\n' % omode)
1284 header.append('old mode %s\n' % omode)
1282 header.append('new mode %s\n' % nmode)
1285 header.append('new mode %s\n' % nmode)
1283
1286
1284 if f in added:
1287 if f in added:
1285 mode = gitmode(execf2(f), linkf2(f))
1288 mode = gitmode(execf2(f), linkf2(f))
1286 if f in copied:
1289 if f in copied:
1287 a = copied[f]
1290 a = copied[f]
1288 omode = gitmode(man1.execf(a), man1.linkf(a))
1291 omode = gitmode(man1.execf(a), man1.linkf(a))
1289 addmodehdr(header, omode, mode)
1292 addmodehdr(header, omode, mode)
1290 if a in removed and a not in gone:
1293 if a in removed and a not in gone:
1291 op = 'rename'
1294 op = 'rename'
1292 gone[a] = 1
1295 gone[a] = 1
1293 else:
1296 else:
1294 op = 'copy'
1297 op = 'copy'
1295 header.append('%s from %s\n' % (op, a))
1298 header.append('%s from %s\n' % (op, a))
1296 header.append('%s to %s\n' % (op, f))
1299 header.append('%s to %s\n' % (op, f))
1297 to = getfilectx(a, ctx1).data()
1300 to = getfilectx(a, ctx1).data()
1298 else:
1301 else:
1299 header.append('new file mode %s\n' % mode)
1302 header.append('new file mode %s\n' % mode)
1300 if util.binary(tn):
1303 if util.binary(tn):
1301 dodiff = 'binary'
1304 dodiff = 'binary'
1302 elif f in removed:
1305 elif f in removed:
1303 if f in srcs:
1306 if f in srcs:
1304 dodiff = False
1307 dodiff = False
1305 else:
1308 else:
1306 mode = gitmode(man1.execf(f), man1.linkf(f))
1309 mode = gitmode(man1.execf(f), man1.linkf(f))
1307 header.append('deleted file mode %s\n' % mode)
1310 header.append('deleted file mode %s\n' % mode)
1308 else:
1311 else:
1309 omode = gitmode(man1.execf(f), man1.linkf(f))
1312 omode = gitmode(man1.execf(f), man1.linkf(f))
1310 nmode = gitmode(execf2(f), linkf2(f))
1313 nmode = gitmode(execf2(f), linkf2(f))
1311 addmodehdr(header, omode, nmode)
1314 addmodehdr(header, omode, nmode)
1312 if util.binary(to) or util.binary(tn):
1315 if util.binary(to) or util.binary(tn):
1313 dodiff = 'binary'
1316 dodiff = 'binary'
1314 r = None
1317 r = None
1315 header.insert(0, 'diff --git a/%s b/%s\n' % (a, b))
1318 header.insert(0, 'diff --git a/%s b/%s\n' % (a, b))
1316 if dodiff:
1319 if dodiff:
1317 if dodiff == 'binary':
1320 if dodiff == 'binary':
1318 text = b85diff(to, tn)
1321 text = b85diff(to, tn)
1319 else:
1322 else:
1320 text = mdiff.unidiff(to, date1,
1323 text = mdiff.unidiff(to, date1,
1321 # ctx2 date may be dynamic
1324 # ctx2 date may be dynamic
1322 tn, util.datestr(ctx2.date()),
1325 tn, util.datestr(ctx2.date()),
1323 a, b, r, opts=opts)
1326 a, b, r, opts=opts)
1324 if text or len(header) > 1:
1327 if text or len(header) > 1:
1325 fp.write(''.join(header))
1328 fp.write(''.join(header))
1326 fp.write(text)
1329 fp.write(text)
1327
1330
1328 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
1331 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
1329 opts=None):
1332 opts=None):
1330 '''export changesets as hg patches.'''
1333 '''export changesets as hg patches.'''
1331
1334
1332 total = len(revs)
1335 total = len(revs)
1333 revwidth = max([len(str(rev)) for rev in revs])
1336 revwidth = max([len(str(rev)) for rev in revs])
1334
1337
1335 def single(rev, seqno, fp):
1338 def single(rev, seqno, fp):
1336 ctx = repo.changectx(rev)
1339 ctx = repo.changectx(rev)
1337 node = ctx.node()
1340 node = ctx.node()
1338 parents = [p.node() for p in ctx.parents() if p]
1341 parents = [p.node() for p in ctx.parents() if p]
1339 branch = ctx.branch()
1342 branch = ctx.branch()
1340 if switch_parent:
1343 if switch_parent:
1341 parents.reverse()
1344 parents.reverse()
1342 prev = (parents and parents[0]) or nullid
1345 prev = (parents and parents[0]) or nullid
1343
1346
1344 if not fp:
1347 if not fp:
1345 fp = cmdutil.make_file(repo, template, node, total=total,
1348 fp = cmdutil.make_file(repo, template, node, total=total,
1346 seqno=seqno, revwidth=revwidth)
1349 seqno=seqno, revwidth=revwidth)
1347 if fp != sys.stdout and hasattr(fp, 'name'):
1350 if fp != sys.stdout and hasattr(fp, 'name'):
1348 repo.ui.note("%s\n" % fp.name)
1351 repo.ui.note("%s\n" % fp.name)
1349
1352
1350 fp.write("# HG changeset patch\n")
1353 fp.write("# HG changeset patch\n")
1351 fp.write("# User %s\n" % ctx.user())
1354 fp.write("# User %s\n" % ctx.user())
1352 fp.write("# Date %d %d\n" % ctx.date())
1355 fp.write("# Date %d %d\n" % ctx.date())
1353 if branch and (branch != 'default'):
1356 if branch and (branch != 'default'):
1354 fp.write("# Branch %s\n" % branch)
1357 fp.write("# Branch %s\n" % branch)
1355 fp.write("# Node ID %s\n" % hex(node))
1358 fp.write("# Node ID %s\n" % hex(node))
1356 fp.write("# Parent %s\n" % hex(prev))
1359 fp.write("# Parent %s\n" % hex(prev))
1357 if len(parents) > 1:
1360 if len(parents) > 1:
1358 fp.write("# Parent %s\n" % hex(parents[1]))
1361 fp.write("# Parent %s\n" % hex(parents[1]))
1359 fp.write(ctx.description().rstrip())
1362 fp.write(ctx.description().rstrip())
1360 fp.write("\n\n")
1363 fp.write("\n\n")
1361
1364
1362 diff(repo, prev, node, fp=fp, opts=opts)
1365 diff(repo, prev, node, fp=fp, opts=opts)
1363 if fp not in (sys.stdout, repo.ui):
1366 if fp not in (sys.stdout, repo.ui):
1364 fp.close()
1367 fp.close()
1365
1368
1366 for seqno, rev in enumerate(revs):
1369 for seqno, rev in enumerate(revs):
1367 single(rev, seqno+1, fp)
1370 single(rev, seqno+1, fp)
1368
1371
1369 def diffstat(patchlines):
1372 def diffstat(patchlines):
1370 if not util.find_exe('diffstat'):
1373 if not util.find_exe('diffstat'):
1371 return
1374 return
1372 fd, name = tempfile.mkstemp(prefix="hg-patchbomb-", suffix=".txt")
1375 fd, name = tempfile.mkstemp(prefix="hg-patchbomb-", suffix=".txt")
1373 try:
1376 try:
1374 p = popen2.Popen3('diffstat -p1 -w79 2>/dev/null > ' + name)
1377 p = popen2.Popen3('diffstat -p1 -w79 2>/dev/null > ' + name)
1375 try:
1378 try:
1376 for line in patchlines:
1379 for line in patchlines:
1377 p.tochild.write(line + "\n")
1380 p.tochild.write(line + "\n")
1378 p.tochild.close()
1381 p.tochild.close()
1379 if p.wait(): return
1382 if p.wait(): return
1380 fp = os.fdopen(fd, 'r')
1383 fp = os.fdopen(fd, 'r')
1381 stat = []
1384 stat = []
1382 for line in fp: stat.append(line.lstrip())
1385 for line in fp: stat.append(line.lstrip())
1383 last = stat.pop()
1386 last = stat.pop()
1384 stat.insert(0, last)
1387 stat.insert(0, last)
1385 stat = ''.join(stat)
1388 stat = ''.join(stat)
1386 return stat
1389 return stat
1387 except: raise
1390 except: raise
1388 finally:
1391 finally:
1389 try: os.unlink(name)
1392 try: os.unlink(name)
1390 except: pass
1393 except: pass
@@ -1,209 +1,227 b''
1 #!/bin/sh
1 #!/bin/sh
2
2
3 hg init a
3 hg init a
4 mkdir a/d1
4 mkdir a/d1
5 mkdir a/d1/d2
5 mkdir a/d1/d2
6 echo line 1 > a/a
6 echo line 1 > a/a
7 echo line 1 > a/d1/d2/a
7 echo line 1 > a/d1/d2/a
8 hg --cwd a ci -d '0 0' -Ama
8 hg --cwd a ci -d '0 0' -Ama
9
9
10 echo line 2 >> a/a
10 echo line 2 >> a/a
11 hg --cwd a ci -u someone -d '1 0' -m'second change'
11 hg --cwd a ci -u someone -d '1 0' -m'second change'
12
12
13 echo % import exported patch
13 echo % import exported patch
14 hg clone -r0 a b
14 hg clone -r0 a b
15 hg --cwd a export tip > tip.patch
15 hg --cwd a export tip > tip.patch
16 hg --cwd b import ../tip.patch
16 hg --cwd b import ../tip.patch
17 echo % message should be same
17 echo % message should be same
18 hg --cwd b tip | grep 'second change'
18 hg --cwd b tip | grep 'second change'
19 echo % committer should be same
19 echo % committer should be same
20 hg --cwd b tip | grep someone
20 hg --cwd b tip | grep someone
21 rm -r b
21 rm -r b
22
22
23 echo % import of plain diff should fail without message
23 echo % import of plain diff should fail without message
24 hg clone -r0 a b
24 hg clone -r0 a b
25 hg --cwd a diff -r0:1 > tip.patch
25 hg --cwd a diff -r0:1 > tip.patch
26 hg --cwd b import ../tip.patch
26 hg --cwd b import ../tip.patch
27 rm -r b
27 rm -r b
28
28
29 echo % import of plain diff should be ok with message
29 echo % import of plain diff should be ok with message
30 hg clone -r0 a b
30 hg clone -r0 a b
31 hg --cwd a diff -r0:1 > tip.patch
31 hg --cwd a diff -r0:1 > tip.patch
32 hg --cwd b import -mpatch ../tip.patch
32 hg --cwd b import -mpatch ../tip.patch
33 rm -r b
33 rm -r b
34
34
35 echo % import of plain diff with specific date and user
35 echo % import of plain diff with specific date and user
36 hg clone -r0 a b
36 hg clone -r0 a b
37 hg --cwd a diff -r0:1 > tip.patch
37 hg --cwd a diff -r0:1 > tip.patch
38 hg --cwd b import -mpatch -d '1 0' -u 'user@nowhere.net' ../tip.patch
38 hg --cwd b import -mpatch -d '1 0' -u 'user@nowhere.net' ../tip.patch
39 hg -R b tip -pv
39 hg -R b tip -pv
40 rm -r b
40 rm -r b
41
41
42 echo % import of plain diff should be ok with --no-commit
42 echo % import of plain diff should be ok with --no-commit
43 hg clone -r0 a b
43 hg clone -r0 a b
44 hg --cwd a diff -r0:1 > tip.patch
44 hg --cwd a diff -r0:1 > tip.patch
45 hg --cwd b import --no-commit ../tip.patch
45 hg --cwd b import --no-commit ../tip.patch
46 hg --cwd b diff --nodates
46 hg --cwd b diff --nodates
47 rm -r b
47 rm -r b
48
48
49 echo % hg -R repo import
49 echo % hg -R repo import
50 # put the clone in a subdir - having a directory named "a"
50 # put the clone in a subdir - having a directory named "a"
51 # used to hide a bug.
51 # used to hide a bug.
52 mkdir dir
52 mkdir dir
53 hg clone -r0 a dir/b
53 hg clone -r0 a dir/b
54 hg --cwd a export tip > dir/tip.patch
54 hg --cwd a export tip > dir/tip.patch
55 cd dir
55 cd dir
56 hg -R b import tip.patch
56 hg -R b import tip.patch
57 cd ..
57 cd ..
58 rm -r dir
58 rm -r dir
59
59
60 echo % import from stdin
60 echo % import from stdin
61 hg clone -r0 a b
61 hg clone -r0 a b
62 hg --cwd a export tip | hg --cwd b import -
62 hg --cwd a export tip | hg --cwd b import -
63 rm -r b
63 rm -r b
64
64
65 echo % override commit message
65 echo % override commit message
66 hg clone -r0 a b
66 hg clone -r0 a b
67 hg --cwd a export tip | hg --cwd b import -m 'override' -
67 hg --cwd a export tip | hg --cwd b import -m 'override' -
68 hg --cwd b tip | grep override
68 hg --cwd b tip | grep override
69 rm -r b
69 rm -r b
70
70
71 cat > mkmsg.py <<EOF
71 cat > mkmsg.py <<EOF
72 import email.Message, sys
72 import email.Message, sys
73 msg = email.Message.Message()
73 msg = email.Message.Message()
74 msg.set_payload('email commit message\n' + open('tip.patch', 'rb').read())
74 msg.set_payload('email commit message\n' + open('tip.patch', 'rb').read())
75 msg['Subject'] = 'email patch'
75 msg['Subject'] = 'email patch'
76 msg['From'] = 'email patcher'
76 msg['From'] = 'email patcher'
77 sys.stdout.write(msg.as_string())
77 sys.stdout.write(msg.as_string())
78 EOF
78 EOF
79
79
80 echo % plain diff in email, subject, message body
80 echo % plain diff in email, subject, message body
81 hg clone -r0 a b
81 hg clone -r0 a b
82 hg --cwd a diff -r0:1 > tip.patch
82 hg --cwd a diff -r0:1 > tip.patch
83 python mkmsg.py > msg.patch
83 python mkmsg.py > msg.patch
84 hg --cwd b import ../msg.patch
84 hg --cwd b import ../msg.patch
85 hg --cwd b tip | grep email
85 hg --cwd b tip | grep email
86 rm -r b
86 rm -r b
87
87
88 echo % plain diff in email, no subject, message body
88 echo % plain diff in email, no subject, message body
89 hg clone -r0 a b
89 hg clone -r0 a b
90 grep -v '^Subject:' msg.patch | hg --cwd b import -
90 grep -v '^Subject:' msg.patch | hg --cwd b import -
91 rm -r b
91 rm -r b
92
92
93 echo % plain diff in email, subject, no message body
93 echo % plain diff in email, subject, no message body
94 hg clone -r0 a b
94 hg clone -r0 a b
95 grep -v '^email ' msg.patch | hg --cwd b import -
95 grep -v '^email ' msg.patch | hg --cwd b import -
96 rm -r b
96 rm -r b
97
97
98 echo % plain diff in email, no subject, no message body, should fail
98 echo % plain diff in email, no subject, no message body, should fail
99 hg clone -r0 a b
99 hg clone -r0 a b
100 egrep -v '^(Subject|email)' msg.patch | hg --cwd b import -
100 egrep -v '^(Subject|email)' msg.patch | hg --cwd b import -
101 rm -r b
101 rm -r b
102
102
103 echo % hg export in email, should use patch header
103 echo % hg export in email, should use patch header
104 hg clone -r0 a b
104 hg clone -r0 a b
105 hg --cwd a export tip > tip.patch
105 hg --cwd a export tip > tip.patch
106 python mkmsg.py | hg --cwd b import -
106 python mkmsg.py | hg --cwd b import -
107 hg --cwd b tip | grep second
107 hg --cwd b tip | grep second
108 rm -r b
108 rm -r b
109
109
110 # subject: duplicate detection, removal of [PATCH]
110 # subject: duplicate detection, removal of [PATCH]
111 # The '---' tests the gitsendmail handling without proper mail headers
111 # The '---' tests the gitsendmail handling without proper mail headers
112 cat > mkmsg2.py <<EOF
112 cat > mkmsg2.py <<EOF
113 import email.Message, sys
113 import email.Message, sys
114 msg = email.Message.Message()
114 msg = email.Message.Message()
115 msg.set_payload('email patch\n\nnext line\n---\n' + open('tip.patch').read())
115 msg.set_payload('email patch\n\nnext line\n---\n' + open('tip.patch').read())
116 msg['Subject'] = '[PATCH] email patch'
116 msg['Subject'] = '[PATCH] email patch'
117 msg['From'] = 'email patcher'
117 msg['From'] = 'email patcher'
118 sys.stdout.write(msg.as_string())
118 sys.stdout.write(msg.as_string())
119 EOF
119 EOF
120
120
121 echo '% plain diff in email, [PATCH] subject, message body with subject'
121 echo '% plain diff in email, [PATCH] subject, message body with subject'
122 hg clone -r0 a b
122 hg clone -r0 a b
123 hg --cwd a diff -r0:1 > tip.patch
123 hg --cwd a diff -r0:1 > tip.patch
124 python mkmsg2.py | hg --cwd b import -
124 python mkmsg2.py | hg --cwd b import -
125 hg --cwd b tip --template '{desc}\n'
125 hg --cwd b tip --template '{desc}\n'
126 rm -r b
126 rm -r b
127
127
128 # We weren't backing up the correct dirstate file when importing many patches
128 # We weren't backing up the correct dirstate file when importing many patches
129 # (issue963)
129 # (issue963)
130 echo '% import patch1 patch2; rollback'
130 echo '% import patch1 patch2; rollback'
131 echo line 3 >> a/a
131 echo line 3 >> a/a
132 hg --cwd a ci -m'third change'
132 hg --cwd a ci -m'third change'
133 hg --cwd a export -o '../patch%R' 1 2
133 hg --cwd a export -o '../patch%R' 1 2
134 hg clone -qr0 a b
134 hg clone -qr0 a b
135 hg --cwd b parents --template 'parent: #rev#\n'
135 hg --cwd b parents --template 'parent: #rev#\n'
136 hg --cwd b import ../patch1 ../patch2
136 hg --cwd b import ../patch1 ../patch2
137 hg --cwd b rollback
137 hg --cwd b rollback
138 hg --cwd b parents --template 'parent: #rev#\n'
138 hg --cwd b parents --template 'parent: #rev#\n'
139 rm -r b
139 rm -r b
140
140
141 # bug non regression test
141 # bug non regression test
142 # importing a patch in a subdirectory failed at the commit stage
142 # importing a patch in a subdirectory failed at the commit stage
143 echo line 2 >> a/d1/d2/a
143 echo line 2 >> a/d1/d2/a
144 hg --cwd a ci -u someoneelse -d '1 0' -m'subdir change'
144 hg --cwd a ci -u someoneelse -d '1 0' -m'subdir change'
145 echo % hg import in a subdirectory
145 echo % hg import in a subdirectory
146 hg clone -r0 a b
146 hg clone -r0 a b
147 hg --cwd a export tip | sed -e 's/d1\/d2\///' > tip.patch
147 hg --cwd a export tip | sed -e 's/d1\/d2\///' > tip.patch
148 dir=`pwd`
148 dir=`pwd`
149 cd b/d1/d2 2>&1 > /dev/null
149 cd b/d1/d2 2>&1 > /dev/null
150 hg import ../../../tip.patch
150 hg import ../../../tip.patch
151 cd $dir
151 cd $dir
152 echo "% message should be 'subdir change'"
152 echo "% message should be 'subdir change'"
153 hg --cwd b tip | grep 'subdir change'
153 hg --cwd b tip | grep 'subdir change'
154 echo "% committer should be 'someoneelse'"
154 echo "% committer should be 'someoneelse'"
155 hg --cwd b tip | grep someoneelse
155 hg --cwd b tip | grep someoneelse
156 echo "% should be empty"
156 echo "% should be empty"
157 hg --cwd b status
157 hg --cwd b status
158
158
159
159
160 # Test fuzziness (ambiguous patch location, fuzz=2)
160 # Test fuzziness (ambiguous patch location, fuzz=2)
161 echo % test fuzziness
161 echo % test fuzziness
162 hg init fuzzy
162 hg init fuzzy
163 cd fuzzy
163 cd fuzzy
164 echo line1 > a
164 echo line1 > a
165 echo line0 >> a
165 echo line0 >> a
166 echo line3 >> a
166 echo line3 >> a
167 hg ci -Am adda
167 hg ci -Am adda
168 echo line1 > a
168 echo line1 > a
169 echo line2 >> a
169 echo line2 >> a
170 echo line0 >> a
170 echo line0 >> a
171 echo line3 >> a
171 echo line3 >> a
172 hg ci -m change a
172 hg ci -m change a
173 hg export tip > tip.patch
173 hg export tip > tip.patch
174 hg up -C 0
174 hg up -C 0
175 echo line1 > a
175 echo line1 > a
176 echo line0 >> a
176 echo line0 >> a
177 echo line1 >> a
177 echo line1 >> a
178 echo line0 >> a
178 echo line0 >> a
179 hg ci -m brancha
179 hg ci -m brancha
180 hg import -v tip.patch
180 hg import -v tip.patch
181 cd ..
181 cd ..
182
182
183 # Test hunk touching empty files (issue906)
183 # Test hunk touching empty files (issue906)
184 hg init empty
184 hg init empty
185 cd empty
185 cd empty
186 touch a
186 touch a
187 touch b1
187 touch b1
188 touch c1
188 touch c1
189 echo d > d
189 echo d > d
190 hg ci -Am init
190 hg ci -Am init
191 echo a > a
191 echo a > a
192 echo b > b1
192 echo b > b1
193 hg mv b1 b2
193 hg mv b1 b2
194 echo c > c1
194 echo c > c1
195 hg copy c1 c2
195 hg copy c1 c2
196 rm d
196 rm d
197 touch d
197 touch d
198 hg diff --git
198 hg diff --git
199 hg ci -m empty
199 hg ci -m empty
200 hg export --git tip > empty.diff
200 hg export --git tip > empty.diff
201 hg up -C 0
201 hg up -C 0
202 hg import empty.diff
202 hg import empty.diff
203 for name in a b1 b2 c1 c2 d;
203 for name in a b1 b2 c1 c2 d;
204 do
204 do
205 echo % $name file
205 echo % $name file
206 test -f $name && cat $name
206 test -f $name && cat $name
207 done
207 done
208 cd ..
208 cd ..
209
209
210 # Test importing a patch ending with a binary file removal
211 echo % test trailing binary removal
212 hg init binaryremoval
213 cd binaryremoval
214 echo a > a
215 python -c "file('b', 'wb').write('a\x00b')"
216 hg ci -Am addall
217 hg rm a
218 hg rm b
219 hg st
220 hg ci -m remove
221 hg export --git . > remove.diff
222 cat remove.diff | grep git
223 hg up -C 0
224 hg import remove.diff
225 hg manifest
226 cd ..
227
@@ -1,225 +1,234 b''
1 adding a
1 adding a
2 adding d1/d2/a
2 adding d1/d2/a
3 % import exported patch
3 % import exported patch
4 requesting all changes
4 requesting all changes
5 adding changesets
5 adding changesets
6 adding manifests
6 adding manifests
7 adding file changes
7 adding file changes
8 added 1 changesets with 2 changes to 2 files
8 added 1 changesets with 2 changes to 2 files
9 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
9 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
10 applying ../tip.patch
10 applying ../tip.patch
11 % message should be same
11 % message should be same
12 summary: second change
12 summary: second change
13 % committer should be same
13 % committer should be same
14 user: someone
14 user: someone
15 % import of plain diff should fail without message
15 % import of plain diff should fail without message
16 requesting all changes
16 requesting all changes
17 adding changesets
17 adding changesets
18 adding manifests
18 adding manifests
19 adding file changes
19 adding file changes
20 added 1 changesets with 2 changes to 2 files
20 added 1 changesets with 2 changes to 2 files
21 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
21 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
22 applying ../tip.patch
22 applying ../tip.patch
23 transaction abort!
23 transaction abort!
24 rollback completed
24 rollback completed
25 abort: empty commit message
25 abort: empty commit message
26 % import of plain diff should be ok with message
26 % import of plain diff should be ok with message
27 requesting all changes
27 requesting all changes
28 adding changesets
28 adding changesets
29 adding manifests
29 adding manifests
30 adding file changes
30 adding file changes
31 added 1 changesets with 2 changes to 2 files
31 added 1 changesets with 2 changes to 2 files
32 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
32 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
33 applying ../tip.patch
33 applying ../tip.patch
34 % import of plain diff with specific date and user
34 % import of plain diff with specific date and user
35 requesting all changes
35 requesting all changes
36 adding changesets
36 adding changesets
37 adding manifests
37 adding manifests
38 adding file changes
38 adding file changes
39 added 1 changesets with 2 changes to 2 files
39 added 1 changesets with 2 changes to 2 files
40 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
40 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
41 applying ../tip.patch
41 applying ../tip.patch
42 changeset: 1:ca68f19f3a40
42 changeset: 1:ca68f19f3a40
43 tag: tip
43 tag: tip
44 user: user@nowhere.net
44 user: user@nowhere.net
45 date: Thu Jan 01 00:00:01 1970 +0000
45 date: Thu Jan 01 00:00:01 1970 +0000
46 files: a
46 files: a
47 description:
47 description:
48 patch
48 patch
49
49
50
50
51 diff -r 80971e65b431 -r ca68f19f3a40 a
51 diff -r 80971e65b431 -r ca68f19f3a40 a
52 --- a/a Thu Jan 01 00:00:00 1970 +0000
52 --- a/a Thu Jan 01 00:00:00 1970 +0000
53 +++ b/a Thu Jan 01 00:00:01 1970 +0000
53 +++ b/a Thu Jan 01 00:00:01 1970 +0000
54 @@ -1,1 +1,2 @@
54 @@ -1,1 +1,2 @@
55 line 1
55 line 1
56 +line 2
56 +line 2
57
57
58 % import of plain diff should be ok with --no-commit
58 % import of plain diff should be ok with --no-commit
59 requesting all changes
59 requesting all changes
60 adding changesets
60 adding changesets
61 adding manifests
61 adding manifests
62 adding file changes
62 adding file changes
63 added 1 changesets with 2 changes to 2 files
63 added 1 changesets with 2 changes to 2 files
64 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
64 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
65 applying ../tip.patch
65 applying ../tip.patch
66 diff -r 80971e65b431 a
66 diff -r 80971e65b431 a
67 --- a/a
67 --- a/a
68 +++ b/a
68 +++ b/a
69 @@ -1,1 +1,2 @@
69 @@ -1,1 +1,2 @@
70 line 1
70 line 1
71 +line 2
71 +line 2
72 % hg -R repo import
72 % hg -R repo import
73 requesting all changes
73 requesting all changes
74 adding changesets
74 adding changesets
75 adding manifests
75 adding manifests
76 adding file changes
76 adding file changes
77 added 1 changesets with 2 changes to 2 files
77 added 1 changesets with 2 changes to 2 files
78 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
78 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
79 applying tip.patch
79 applying tip.patch
80 % import from stdin
80 % import from stdin
81 requesting all changes
81 requesting all changes
82 adding changesets
82 adding changesets
83 adding manifests
83 adding manifests
84 adding file changes
84 adding file changes
85 added 1 changesets with 2 changes to 2 files
85 added 1 changesets with 2 changes to 2 files
86 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
86 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
87 applying patch from stdin
87 applying patch from stdin
88 % override commit message
88 % override commit message
89 requesting all changes
89 requesting all changes
90 adding changesets
90 adding changesets
91 adding manifests
91 adding manifests
92 adding file changes
92 adding file changes
93 added 1 changesets with 2 changes to 2 files
93 added 1 changesets with 2 changes to 2 files
94 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
94 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
95 applying patch from stdin
95 applying patch from stdin
96 summary: override
96 summary: override
97 % plain diff in email, subject, message body
97 % plain diff in email, subject, message body
98 requesting all changes
98 requesting all changes
99 adding changesets
99 adding changesets
100 adding manifests
100 adding manifests
101 adding file changes
101 adding file changes
102 added 1 changesets with 2 changes to 2 files
102 added 1 changesets with 2 changes to 2 files
103 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
103 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
104 applying ../msg.patch
104 applying ../msg.patch
105 user: email patcher
105 user: email patcher
106 summary: email patch
106 summary: email patch
107 % plain diff in email, no subject, message body
107 % plain diff in email, no subject, message body
108 requesting all changes
108 requesting all changes
109 adding changesets
109 adding changesets
110 adding manifests
110 adding manifests
111 adding file changes
111 adding file changes
112 added 1 changesets with 2 changes to 2 files
112 added 1 changesets with 2 changes to 2 files
113 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
113 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
114 applying patch from stdin
114 applying patch from stdin
115 % plain diff in email, subject, no message body
115 % plain diff in email, subject, no message body
116 requesting all changes
116 requesting all changes
117 adding changesets
117 adding changesets
118 adding manifests
118 adding manifests
119 adding file changes
119 adding file changes
120 added 1 changesets with 2 changes to 2 files
120 added 1 changesets with 2 changes to 2 files
121 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
121 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
122 applying patch from stdin
122 applying patch from stdin
123 % plain diff in email, no subject, no message body, should fail
123 % plain diff in email, no subject, no message body, should fail
124 requesting all changes
124 requesting all changes
125 adding changesets
125 adding changesets
126 adding manifests
126 adding manifests
127 adding file changes
127 adding file changes
128 added 1 changesets with 2 changes to 2 files
128 added 1 changesets with 2 changes to 2 files
129 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
129 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
130 applying patch from stdin
130 applying patch from stdin
131 transaction abort!
131 transaction abort!
132 rollback completed
132 rollback completed
133 abort: empty commit message
133 abort: empty commit message
134 % hg export in email, should use patch header
134 % hg export in email, should use patch header
135 requesting all changes
135 requesting all changes
136 adding changesets
136 adding changesets
137 adding manifests
137 adding manifests
138 adding file changes
138 adding file changes
139 added 1 changesets with 2 changes to 2 files
139 added 1 changesets with 2 changes to 2 files
140 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
140 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
141 applying patch from stdin
141 applying patch from stdin
142 summary: second change
142 summary: second change
143 % plain diff in email, [PATCH] subject, message body with subject
143 % plain diff in email, [PATCH] subject, message body with subject
144 requesting all changes
144 requesting all changes
145 adding changesets
145 adding changesets
146 adding manifests
146 adding manifests
147 adding file changes
147 adding file changes
148 added 1 changesets with 2 changes to 2 files
148 added 1 changesets with 2 changes to 2 files
149 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
149 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
150 applying patch from stdin
150 applying patch from stdin
151 email patch
151 email patch
152
152
153 next line
153 next line
154 ---
154 ---
155 % import patch1 patch2; rollback
155 % import patch1 patch2; rollback
156 parent: 0
156 parent: 0
157 applying ../patch1
157 applying ../patch1
158 applying ../patch2
158 applying ../patch2
159 rolling back last transaction
159 rolling back last transaction
160 parent: 1
160 parent: 1
161 % hg import in a subdirectory
161 % hg import in a subdirectory
162 requesting all changes
162 requesting all changes
163 adding changesets
163 adding changesets
164 adding manifests
164 adding manifests
165 adding file changes
165 adding file changes
166 added 1 changesets with 2 changes to 2 files
166 added 1 changesets with 2 changes to 2 files
167 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
167 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
168 applying ../../../tip.patch
168 applying ../../../tip.patch
169 % message should be 'subdir change'
169 % message should be 'subdir change'
170 summary: subdir change
170 summary: subdir change
171 % committer should be 'someoneelse'
171 % committer should be 'someoneelse'
172 user: someoneelse
172 user: someoneelse
173 % should be empty
173 % should be empty
174 % test fuzziness
174 % test fuzziness
175 adding a
175 adding a
176 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
176 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
177 applying tip.patch
177 applying tip.patch
178 patching file a
178 patching file a
179 Hunk #1 succeeded at 1 with fuzz 2 (offset -2 lines).
179 Hunk #1 succeeded at 1 with fuzz 2 (offset -2 lines).
180 a
180 a
181 adding a
181 adding a
182 adding b1
182 adding b1
183 adding c1
183 adding c1
184 adding d
184 adding d
185 diff --git a/a b/a
185 diff --git a/a b/a
186 --- a/a
186 --- a/a
187 +++ b/a
187 +++ b/a
188 @@ -0,0 +1,1 @@
188 @@ -0,0 +1,1 @@
189 +a
189 +a
190 diff --git a/b1 b/b2
190 diff --git a/b1 b/b2
191 rename from b1
191 rename from b1
192 rename to b2
192 rename to b2
193 --- a/b1
193 --- a/b1
194 +++ b/b2
194 +++ b/b2
195 @@ -0,0 +1,1 @@
195 @@ -0,0 +1,1 @@
196 +b
196 +b
197 diff --git a/c1 b/c1
197 diff --git a/c1 b/c1
198 --- a/c1
198 --- a/c1
199 +++ b/c1
199 +++ b/c1
200 @@ -0,0 +1,1 @@
200 @@ -0,0 +1,1 @@
201 +c
201 +c
202 diff --git a/c1 b/c2
202 diff --git a/c1 b/c2
203 copy from c1
203 copy from c1
204 copy to c2
204 copy to c2
205 --- a/c1
205 --- a/c1
206 +++ b/c2
206 +++ b/c2
207 @@ -0,0 +1,1 @@
207 @@ -0,0 +1,1 @@
208 +c
208 +c
209 diff --git a/d b/d
209 diff --git a/d b/d
210 --- a/d
210 --- a/d
211 +++ b/d
211 +++ b/d
212 @@ -1,1 +0,0 @@
212 @@ -1,1 +0,0 @@
213 -d
213 -d
214 4 files updated, 0 files merged, 2 files removed, 0 files unresolved
214 4 files updated, 0 files merged, 2 files removed, 0 files unresolved
215 applying empty.diff
215 applying empty.diff
216 % a file
216 % a file
217 a
217 a
218 % b1 file
218 % b1 file
219 % b2 file
219 % b2 file
220 b
220 b
221 % c1 file
221 % c1 file
222 c
222 c
223 % c2 file
223 % c2 file
224 c
224 c
225 % d file
225 % d file
226 % test trailing binary removal
227 adding a
228 adding b
229 R a
230 R b
231 diff --git a/a b/a
232 diff --git a/b b/b
233 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
234 applying remove.diff
General Comments 0
You need to be logged in to leave comments. Login now