##// END OF EJS Templates
extensions: use new wrapper functions
Matt Mackall -
r7216:292fb2ad default
parent child Browse files
Show More
@@ -1,225 +1,190 b''
1 1 # color.py color output for the status and qseries commands
2 2 #
3 3 # Copyright (C) 2007 Kevin Christen <kevin.christen@gmail.com>
4 4 #
5 5 # This program is free software; you can redistribute it and/or modify it
6 6 # under the terms of the GNU General Public License as published by the
7 7 # Free Software Foundation; either version 2 of the License, or (at your
8 8 # option) any later version.
9 9 #
10 10 # This program is distributed in the hope that it will be useful, but
11 11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
13 13 # Public License for more details.
14 14 #
15 15 # You should have received a copy of the GNU General Public License along
16 16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 18
19 19 '''add color output to the status and qseries commands
20 20
21 21 This extension modifies the status command to add color to its output to
22 22 reflect file status, and the qseries command to add color to reflect patch
23 23 status (applied, unapplied, missing). Other effects in addition to color,
24 24 like bold and underlined text, are also available. Effects are rendered
25 25 with the ECMA-48 SGR control function (aka ANSI escape codes). This module
26 26 also provides the render_text function, which can be used to add effects to
27 27 any text.
28 28
29 29 To enable this extension, add this to your .hgrc file:
30 30 [extensions]
31 31 color =
32 32
33 33 Default effects my be overriden from the .hgrc file:
34 34
35 35 [color]
36 36 status.modified = blue bold underline red_background
37 37 status.added = green bold
38 38 status.removed = red bold blue_background
39 39 status.deleted = cyan bold underline
40 40 status.unknown = magenta bold underline
41 41 status.ignored = black bold
42 42
43 43 # 'none' turns off all effects
44 44 status.clean = none
45 45 status.copied = none
46 46
47 47 qseries.applied = blue bold underline
48 48 qseries.unapplied = black bold
49 49 qseries.missing = red bold
50 50 '''
51 51
52 52 import re, sys
53 53
54 from mercurial import commands, cmdutil
54 from mercurial import commands, cmdutil, extensions
55 55 from mercurial.i18n import _
56 56
57 57 # start and stop parameters for effects
58 58 _effect_params = { 'none': (0, 0),
59 59 'black': (30, 39),
60 60 'red': (31, 39),
61 61 'green': (32, 39),
62 62 'yellow': (33, 39),
63 63 'blue': (34, 39),
64 64 'magenta': (35, 39),
65 65 'cyan': (36, 39),
66 66 'white': (37, 39),
67 67 'bold': (1, 22),
68 68 'italic': (3, 23),
69 69 'underline': (4, 24),
70 70 'inverse': (7, 27),
71 71 'black_background': (40, 49),
72 72 'red_background': (41, 49),
73 73 'green_background': (42, 49),
74 74 'yellow_background': (43, 49),
75 75 'blue_background': (44, 49),
76 76 'purple_background': (45, 49),
77 77 'cyan_background': (46, 49),
78 78 'white_background': (47, 49), }
79 79
80 80 def render_effects(text, *effects):
81 81 'Wrap text in commands to turn on each effect.'
82 82 start = [ str(_effect_params['none'][0]) ]
83 83 stop = []
84 84 for effect in effects:
85 85 start.append(str(_effect_params[effect][0]))
86 86 stop.append(str(_effect_params[effect][1]))
87 87 stop.append(str(_effect_params['none'][1]))
88 88 start = '\033[' + ';'.join(start) + 'm'
89 89 stop = '\033[' + ';'.join(stop) + 'm'
90 90 return start + text + stop
91 91
92 def colorstatus(statusfunc, ui, repo, *pats, **opts):
92 def colorstatus(orig, ui, repo, *pats, **opts):
93 93 '''run the status command with colored output'''
94 94
95 95 delimiter = opts['print0'] and '\0' or '\n'
96 96
97 97 # run status and capture it's output
98 98 ui.pushbuffer()
99 retval = statusfunc(ui, repo, *pats, **opts)
99 retval = orig(ui, repo, *pats, **opts)
100 100 # filter out empty strings
101 101 lines = [ line for line in ui.popbuffer().split(delimiter) if line ]
102 102
103 103 if opts['no_status']:
104 104 # if --no-status, run the command again without that option to get
105 105 # output with status abbreviations
106 106 opts['no_status'] = False
107 107 ui.pushbuffer()
108 108 statusfunc(ui, repo, *pats, **opts)
109 109 # filter out empty strings
110 110 lines_with_status = [ line for
111 111 line in ui.popbuffer().split(delimiter) if line ]
112 112 else:
113 113 lines_with_status = lines
114 114
115 115 # apply color to output and display it
116 116 for i in xrange(0, len(lines)):
117 117 status = _status_abbreviations[lines_with_status[i][0]]
118 118 effects = _status_effects[status]
119 119 if effects:
120 120 lines[i] = render_effects(lines[i], *effects)
121 121 sys.stdout.write(lines[i] + delimiter)
122 122 return retval
123 123
124 124 _status_abbreviations = { 'M': 'modified',
125 125 'A': 'added',
126 126 'R': 'removed',
127 127 '!': 'deleted',
128 128 '?': 'unknown',
129 129 'I': 'ignored',
130 130 'C': 'clean',
131 131 ' ': 'copied', }
132 132
133 133 _status_effects = { 'modified': ('blue', 'bold'),
134 134 'added': ('green', 'bold'),
135 135 'removed': ('red', 'bold'),
136 136 'deleted': ('cyan', 'bold', 'underline'),
137 137 'unknown': ('magenta', 'bold', 'underline'),
138 138 'ignored': ('black', 'bold'),
139 139 'clean': ('none', ),
140 140 'copied': ('none', ), }
141 141
142 def colorqseries(qseriesfunc, ui, repo, *dummy, **opts):
142 def colorqseries(orig, ui, repo, *dummy, **opts):
143 143 '''run the qseries command with colored output'''
144 144 ui.pushbuffer()
145 retval = qseriesfunc(ui, repo, **opts)
145 retval = orig(ui, repo, **opts)
146 146 patches = ui.popbuffer().splitlines()
147 147 for patch in patches:
148 148 patchname = patch
149 149 if opts['summary']:
150 150 patchname = patchname.split(': ')[0]
151 151 if ui.verbose:
152 152 patchname = patchname.split(' ', 2)[-1]
153 153
154 154 if opts['missing']:
155 155 effects = _patch_effects['missing']
156 156 # Determine if patch is applied.
157 157 elif [ applied for applied in repo.mq.applied
158 158 if patchname == applied.name ]:
159 159 effects = _patch_effects['applied']
160 160 else:
161 161 effects = _patch_effects['unapplied']
162 162 sys.stdout.write(render_effects(patch, *effects) + '\n')
163 163 return retval
164 164
165 165 _patch_effects = { 'applied': ('blue', 'bold', 'underline'),
166 166 'missing': ('red', 'bold'),
167 167 'unapplied': ('black', 'bold'), }
168 168
169 169 def uisetup(ui):
170 170 '''Initialize the extension.'''
171 nocoloropt = ('', 'no-color', None, _("don't colorize output"))
172 _decoratecmd(ui, 'status', commands.table, colorstatus, nocoloropt)
173 _configcmdeffects(ui, 'status', _status_effects);
171 _setupcmd(ui, 'status', commands.table, colorstatus, _status_effects)
174 172 if ui.config('extensions', 'hgext.mq') is not None or \
175 173 ui.config('extensions', 'mq') is not None:
176 174 from hgext import mq
177 _decoratecmd(ui, 'qseries', mq.cmdtable, colorqseries, nocoloropt)
178 _configcmdeffects(ui, 'qseries', _patch_effects);
179
180 def _decoratecmd(ui, cmd, table, delegate, *delegateoptions):
181 '''Replace the function that implements cmd in table with a decorator.
182
183 The decorator that becomes the new implementation of cmd calls
184 delegate. The delegate's first argument is the replaced function,
185 followed by the normal Mercurial command arguments (ui, repo, ...). If
186 the delegate adds command options, supply them as delegateoptions.
187 '''
188 cmdkey, cmdentry = _cmdtableitem(ui, cmd, table)
189 decorator = lambda ui, repo, *args, **opts: \
190 _colordecorator(delegate, cmdentry[0],
191 ui, repo, *args, **opts)
192 # make sure 'hg help cmd' still works
193 decorator.__doc__ = cmdentry[0].__doc__
194 decoratorentry = (decorator,) + cmdentry[1:]
195 for option in delegateoptions:
196 decoratorentry[1].append(option)
197 table[cmdkey] = decoratorentry
175 _setupcmd(ui, 'qseries', mq.cmdtable, colorqseries, _patch_effects)
198 176
199 def _cmdtableitem(ui, cmd, table):
200 '''Return key, value from table for cmd, or None if not found.'''
201 aliases, entry = cmdutil.findcmd(cmd, table)
202 for candidatekey, candidateentry in table.iteritems():
203 if candidateentry is entry:
204 return candidatekey, entry
205
206 def _colordecorator(colorfunc, nocolorfunc, ui, repo, *args, **opts):
207 '''Delegate to colorfunc or nocolorfunc, depending on conditions.
177 def _setupcmd(ui, cmd, table, func, effectsmap):
178 '''patch in command to command table and load effect map'''
179 def nocolor(orig, *args, **kwargs):
180 if kwargs['no_color']:
181 return orig(*args, **kwargs)
182 return func(orig, *args, **kwargs)
208 183
209 Delegate to colorfunc unless --no-color option is set or output is not
210 to a tty.
211 '''
212 if opts['no_color'] or not sys.stdout.isatty():
213 return nocolorfunc(ui, repo, *args, **opts)
214 return colorfunc(nocolorfunc, ui, repo, *args, **opts)
184 entry = extensions.wrapcommand(table, cmd, nocolor)
185 entry[1].append(('', 'no-color', None, _("don't colorize output")))
215 186
216 def _configcmdeffects(ui, cmdname, effectsmap):
217 '''Override default effects for cmdname with those from .hgrc file.
218
219 Entries in the .hgrc file are in the [color] section, and look like
220 'cmdname'.'status' (for instance, 'status.modified = blue bold inverse').
221 '''
222 187 for status in effectsmap:
223 effects = ui.config('color', cmdname + '.' + status)
188 effects = ui.config('color', cmd + '.' + status)
224 189 if effects:
225 190 effectsmap[status] = re.split('\W+', effects)
@@ -1,61 +1,57 b''
1 1 """syntax highlighting in hgweb, based on Pygments
2 2
3 3 It depends on the pygments syntax highlighting library:
4 4 http://pygments.org/
5 5
6 6 To enable the extension add this to hgrc:
7 7
8 8 [extensions]
9 9 hgext.highlight =
10 10
11 11 There is a single configuration option:
12 12
13 13 [web]
14 14 pygments_style = <style>
15 15
16 16 The default is 'colorful'.
17 17
18 18 -- Adam Hupp <adam@hupp.org>
19 19 """
20 20
21 21 import highlight
22 22 from mercurial.hgweb import webcommands, webutil, common
23 from mercurial import extensions
23 24
24 web_filerevision = webcommands._filerevision
25 web_annotate = webcommands.annotate
26
27 def filerevision_highlight(web, tmpl, fctx):
25 def filerevision_highlight(orig, web, tmpl, fctx):
28 26 mt = ''.join(tmpl('mimetype', encoding=web.encoding))
29 27 # only pygmentize for mimetype containing 'html' so we both match
30 28 # 'text/html' and possibly 'application/xhtml+xml' in the future
31 29 # so that we don't have to touch the extension when the mimetype
32 30 # for a template changes; also hgweb optimizes the case that a
33 31 # raw file is sent using rawfile() and doesn't call us, so we
34 32 # can't clash with the file's content-type here in case we
35 33 # pygmentize a html file
36 34 if 'html' in mt:
37 35 style = web.config('web', 'pygments_style', 'colorful')
38 36 highlight.pygmentize('fileline', fctx, style, tmpl)
39 return web_filerevision(web, tmpl, fctx)
37 return orig(web, tmpl, fctx)
40 38
41 def annotate_highlight(web, req, tmpl):
39 def annotate_highlight(orig, web, req, tmpl):
42 40 mt = ''.join(tmpl('mimetype', encoding=web.encoding))
43 41 if 'html' in mt:
44 42 fctx = webutil.filectx(web.repo, req)
45 43 style = web.config('web', 'pygments_style', 'colorful')
46 44 highlight.pygmentize('annotateline', fctx, style, tmpl)
47 return web_annotate(web, req, tmpl)
45 return orig(web, req, tmpl)
48 46
49 47 def generate_css(web, req, tmpl):
50 48 pg_style = web.config('web', 'pygments_style', 'colorful')
51 49 fmter = highlight.HtmlFormatter(style = pg_style)
52 50 req.respond(common.HTTP_OK, 'text/css')
53 51 return ['/* pygments_style = %s */\n\n' % pg_style, fmter.get_style_defs('')]
54 52
55
56 53 # monkeypatch in the new version
57
58 webcommands._filerevision = filerevision_highlight
59 webcommands.annotate = annotate_highlight
54 extensions.wrapfunction(webcommands, '_filerevision', filerevision_highlight)
55 extensions.wrapfunction(webcommands, 'annotate', annotate_highlight)
60 56 webcommands.highlightcss = generate_css
61 57 webcommands.__all__.append('highlightcss')
@@ -1,84 +1,82 b''
1 1 # interhg.py - interhg
2 2 #
3 3 # Copyright 2007 OHASHI Hideya <ohachige@gmail.com>
4 4 #
5 5 # Contributor(s):
6 6 # Edward Lee <edward.lee@engineering.uiuc.edu>
7 7 #
8 8 # This software may be used and distributed according to the terms
9 9 # of the GNU General Public License, incorporated herein by reference.
10 10 #
11 11 # The `interhg' Mercurial extension allows you to change changelog and
12 12 # summary text just like InterWiki way.
13 13 #
14 14 # To enable this extension:
15 15 #
16 16 # [extensions]
17 17 # interhg =
18 18 #
19 19 # These are some example patterns (link to bug tracking, etc.)
20 20 #
21 21 # [interhg]
22 22 # issues = s!issue(\d+)!<a href="http://bts/issue\1">issue\1<\/a>!
23 23 # bugzilla = s!((?:bug|b=|(?=#?\d{4,}))(?:\s*#?)(\d+))!<a..=\2">\1</a>!i
24 24 # boldify = s/(^|\s)#(\d+)\b/ <b>#\2<\/b>/
25 25 #
26 26 # Add any number of names and patterns to match
27 27
28 28 import re
29 29 from mercurial.hgweb import hgweb_mod
30 from mercurial import templatefilters
30 from mercurial import templatefilters, extensions
31 31 from mercurial.i18n import _
32 32
33 33 orig_escape = templatefilters.filters["escape"]
34 34
35 35 interhg_table = []
36 36
37 37 def interhg_escape(x):
38 38 escstr = orig_escape(x)
39 39 for regexp, format in interhg_table:
40 40 escstr = regexp.sub(format, escstr)
41 41 return escstr
42 42
43 43 templatefilters.filters["escape"] = interhg_escape
44 44
45 orig_refresh = hgweb_mod.hgweb.refresh
46
47 def interhg_refresh(self):
45 def interhg_refresh(orig, self):
48 46 interhg_table[:] = []
49 47 for key, pattern in self.repo.ui.configitems('interhg'):
50 48 # grab the delimiter from the character after the "s"
51 49 unesc = pattern[1]
52 50 delim = re.escape(unesc)
53 51
54 52 # identify portions of the pattern, taking care to avoid escaped
55 53 # delimiters. the replace format and flags are optional, but delimiters
56 54 # are required.
57 55 match = re.match(r'^s%s(.+)(?:(?<=\\\\)|(?<!\\))%s(.*)%s([ilmsux])*$'
58 56 % (delim, delim, delim), pattern)
59 57 if not match:
60 58 self.repo.ui.warn(_("interhg: invalid pattern for %s: %s\n")
61 59 % (key, pattern))
62 60 continue
63 61
64 62 # we need to unescape the delimiter for regexp and format
65 63 delim_re = re.compile(r'(?<!\\)\\%s' % delim)
66 64 regexp = delim_re.sub(unesc, match.group(1))
67 65 format = delim_re.sub(unesc, match.group(2))
68 66
69 67 # the pattern allows for 6 regexp flags, so set them if necessary
70 68 flagin = match.group(3)
71 69 flags = 0
72 70 if flagin:
73 71 for flag in flagin.upper():
74 72 flags |= re.__dict__[flag]
75 73
76 74 try:
77 75 regexp = re.compile(regexp, flags)
78 76 interhg_table.append((regexp, format))
79 77 except re.error:
80 78 self.repo.ui.warn(_("interhg: invalid regexp for %s: %s\n")
81 79 % (key, regexp))
82 return orig_refresh(self)
80 return orig(self)
83 81
84 hgweb_mod.hgweb.refresh = interhg_refresh
82 extensions.wrapfunction(hgweb_mod.hgweb, 'refresh', interhg_refresh)
@@ -1,562 +1,543 b''
1 1 # keyword.py - $Keyword$ expansion for Mercurial
2 2 #
3 3 # Copyright 2007, 2008 Christian Ebert <blacktrash@gmx.net>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7 #
8 8 # $Id$
9 9 #
10 10 # Keyword expansion hack against the grain of a DSCM
11 11 #
12 12 # There are many good reasons why this is not needed in a distributed
13 13 # SCM, still it may be useful in very small projects based on single
14 14 # files (like LaTeX packages), that are mostly addressed to an audience
15 15 # not running a version control system.
16 16 #
17 17 # For in-depth discussion refer to
18 18 # <http://www.selenic.com/mercurial/wiki/index.cgi/KeywordPlan>.
19 19 #
20 20 # Keyword expansion is based on Mercurial's changeset template mappings.
21 21 #
22 22 # Binary files are not touched.
23 23 #
24 24 # Setup in hgrc:
25 25 #
26 26 # [extensions]
27 27 # # enable extension
28 28 # hgext.keyword =
29 29 #
30 30 # Files to act upon/ignore are specified in the [keyword] section.
31 31 # Customized keyword template mappings in the [keywordmaps] section.
32 32 #
33 33 # Run "hg help keyword" and "hg kwdemo" to get info on configuration.
34 34
35 35 '''keyword expansion in local repositories
36 36
37 37 This extension expands RCS/CVS-like or self-customized $Keywords$
38 38 in tracked text files selected by your configuration.
39 39
40 40 Keywords are only expanded in local repositories and not stored in
41 41 the change history. The mechanism can be regarded as a convenience
42 42 for the current user or for archive distribution.
43 43
44 44 Configuration is done in the [keyword] and [keywordmaps] sections
45 45 of hgrc files.
46 46
47 47 Example:
48 48
49 49 [keyword]
50 50 # expand keywords in every python file except those matching "x*"
51 51 **.py =
52 52 x* = ignore
53 53
54 54 Note: the more specific you are in your filename patterns
55 55 the less you lose speed in huge repos.
56 56
57 57 For [keywordmaps] template mapping and expansion demonstration and
58 58 control run "hg kwdemo".
59 59
60 60 An additional date template filter {date|utcdate} is provided.
61 61
62 62 The default template mappings (view with "hg kwdemo -d") can be replaced
63 63 with customized keywords and templates.
64 64 Again, run "hg kwdemo" to control the results of your config changes.
65 65
66 66 Before changing/disabling active keywords, run "hg kwshrink" to avoid
67 67 the risk of inadvertedly storing expanded keywords in the change history.
68 68
69 69 To force expansion after enabling it, or a configuration change, run
70 70 "hg kwexpand".
71 71
72 72 Also, when committing with the record extension or using mq's qrecord, be aware
73 73 that keywords cannot be updated. Again, run "hg kwexpand" on the files in
74 74 question to update keyword expansions after all changes have been checked in.
75 75
76 76 Expansions spanning more than one line and incremental expansions,
77 77 like CVS' $Log$, are not supported. A keyword template map
78 78 "Log = {desc}" expands to the first line of the changeset description.
79 79 '''
80 80
81 from mercurial import commands, cmdutil, dispatch, filelog, revlog
81 from mercurial import commands, cmdutil, dispatch, filelog, revlog, extensions
82 82 from mercurial import patch, localrepo, templater, templatefilters, util
83 83 from mercurial.hgweb import webcommands
84 84 from mercurial.node import nullid, hex
85 85 from mercurial.i18n import _
86 86 import re, shutil, tempfile, time
87 87
88 88 commands.optionalrepo += ' kwdemo'
89 89
90 90 # hg commands that do not act on keywords
91 91 nokwcommands = ('add addremove annotate bundle copy export grep incoming init'
92 92 ' log outgoing push rename rollback tip verify'
93 93 ' convert email glog')
94 94
95 95 # hg commands that trigger expansion only when writing to working dir,
96 96 # not when reading filelog, and unexpand when reading from working dir
97 97 restricted = 'merge record resolve qfold qimport qnew qpush qrefresh qrecord'
98 98
99 99 def utcdate(date):
100 100 '''Returns hgdate in cvs-like UTC format.'''
101 101 return time.strftime('%Y/%m/%d %H:%M:%S', time.gmtime(date[0]))
102 102
103 103 # make keyword tools accessible
104 104 kwtools = {'templater': None, 'hgcmd': '', 'inc': [], 'exc': ['.hg*']}
105 105
106 106
107 107 class kwtemplater(object):
108 108 '''
109 109 Sets up keyword templates, corresponding keyword regex, and
110 110 provides keyword substitution functions.
111 111 '''
112 112 templates = {
113 113 'Revision': '{node|short}',
114 114 'Author': '{author|user}',
115 115 'Date': '{date|utcdate}',
116 116 'RCSFile': '{file|basename},v',
117 117 'Source': '{root}/{file},v',
118 118 'Id': '{file|basename},v {node|short} {date|utcdate} {author|user}',
119 119 'Header': '{root}/{file},v {node|short} {date|utcdate} {author|user}',
120 120 }
121 121
122 122 def __init__(self, ui, repo):
123 123 self.ui = ui
124 124 self.repo = repo
125 125 self.matcher = util.matcher(repo.root,
126 126 inc=kwtools['inc'], exc=kwtools['exc'])[1]
127 127 self.restrict = kwtools['hgcmd'] in restricted.split()
128 128
129 129 kwmaps = self.ui.configitems('keywordmaps')
130 130 if kwmaps: # override default templates
131 131 kwmaps = [(k, templater.parsestring(v, False))
132 132 for (k, v) in kwmaps]
133 133 self.templates = dict(kwmaps)
134 134 escaped = map(re.escape, self.templates.keys())
135 135 kwpat = r'\$(%s)(: [^$\n\r]*? )??\$' % '|'.join(escaped)
136 136 self.re_kw = re.compile(kwpat)
137 137
138 138 templatefilters.filters['utcdate'] = utcdate
139 139 self.ct = cmdutil.changeset_templater(self.ui, self.repo,
140 140 False, '', False)
141 141
142 142 def getnode(self, path, fnode):
143 143 '''Derives changenode from file path and filenode.'''
144 144 # used by kwfilelog.read and kwexpand
145 145 c = self.repo.filectx(path, fileid=fnode)
146 146 return c.node()
147 147
148 148 def substitute(self, data, path, node, subfunc):
149 149 '''Replaces keywords in data with expanded template.'''
150 150 def kwsub(mobj):
151 151 kw = mobj.group(1)
152 152 self.ct.use_template(self.templates[kw])
153 153 self.ui.pushbuffer()
154 154 self.ct.show(changenode=node, root=self.repo.root, file=path)
155 155 ekw = templatefilters.firstline(self.ui.popbuffer())
156 156 return '$%s: %s $' % (kw, ekw)
157 157 return subfunc(kwsub, data)
158 158
159 159 def expand(self, path, node, data):
160 160 '''Returns data with keywords expanded.'''
161 161 if not self.restrict and self.matcher(path) and not util.binary(data):
162 162 changenode = self.getnode(path, node)
163 163 return self.substitute(data, path, changenode, self.re_kw.sub)
164 164 return data
165 165
166 166 def iskwfile(self, path, flagfunc):
167 167 '''Returns true if path matches [keyword] pattern
168 168 and is not a symbolic link.
169 169 Caveat: localrepository._link fails on Windows.'''
170 170 return self.matcher(path) and not 'l' in flagfunc(path)
171 171
172 172 def overwrite(self, node, expand, files):
173 173 '''Overwrites selected files expanding/shrinking keywords.'''
174 174 if node is not None: # commit
175 175 ctx = self.repo[node]
176 176 mf = ctx.manifest()
177 177 files = [f for f in ctx.files() if f in mf]
178 178 notify = self.ui.debug
179 179 else: # kwexpand/kwshrink
180 180 ctx = self.repo['.']
181 181 mf = ctx.manifest()
182 182 notify = self.ui.note
183 183 candidates = [f for f in files if self.iskwfile(f, ctx.flags)]
184 184 if candidates:
185 185 self.restrict = True # do not expand when reading
186 186 action = expand and 'expanding' or 'shrinking'
187 187 for f in candidates:
188 188 fp = self.repo.file(f)
189 189 data = fp.read(mf[f])
190 190 if util.binary(data):
191 191 continue
192 192 if expand:
193 193 changenode = node or self.getnode(f, mf[f])
194 194 data, found = self.substitute(data, f, changenode,
195 195 self.re_kw.subn)
196 196 else:
197 197 found = self.re_kw.search(data)
198 198 if found:
199 199 notify(_('overwriting %s %s keywords\n') % (f, action))
200 200 self.repo.wwrite(f, data, mf.flags(f))
201 201 self.repo.dirstate.normal(f)
202 202 self.restrict = False
203 203
204 204 def shrinktext(self, text):
205 205 '''Unconditionally removes all keyword substitutions from text.'''
206 206 return self.re_kw.sub(r'$\1$', text)
207 207
208 208 def shrink(self, fname, text):
209 209 '''Returns text with all keyword substitutions removed.'''
210 210 if self.matcher(fname) and not util.binary(text):
211 211 return self.shrinktext(text)
212 212 return text
213 213
214 214 def shrinklines(self, fname, lines):
215 215 '''Returns lines with keyword substitutions removed.'''
216 216 if self.matcher(fname):
217 217 text = ''.join(lines)
218 218 if not util.binary(text):
219 219 return self.shrinktext(text).splitlines(True)
220 220 return lines
221 221
222 222 def wread(self, fname, data):
223 223 '''If in restricted mode returns data read from wdir with
224 224 keyword substitutions removed.'''
225 225 return self.restrict and self.shrink(fname, data) or data
226 226
227 227 class kwfilelog(filelog.filelog):
228 228 '''
229 229 Subclass of filelog to hook into its read, add, cmp methods.
230 230 Keywords are "stored" unexpanded, and processed on reading.
231 231 '''
232 232 def __init__(self, opener, kwt, path):
233 233 super(kwfilelog, self).__init__(opener, path)
234 234 self.kwt = kwt
235 235 self.path = path
236 236
237 237 def read(self, node):
238 238 '''Expands keywords when reading filelog.'''
239 239 data = super(kwfilelog, self).read(node)
240 240 return self.kwt.expand(self.path, node, data)
241 241
242 242 def add(self, text, meta, tr, link, p1=None, p2=None):
243 243 '''Removes keyword substitutions when adding to filelog.'''
244 244 text = self.kwt.shrink(self.path, text)
245 245 return super(kwfilelog, self).add(text, meta, tr, link, p1, p2)
246 246
247 247 def cmp(self, node, text):
248 248 '''Removes keyword substitutions for comparison.'''
249 249 text = self.kwt.shrink(self.path, text)
250 250 if self.renamed(node):
251 251 t2 = super(kwfilelog, self).read(node)
252 252 return t2 != text
253 253 return revlog.revlog.cmp(self, node, text)
254 254
255 255 def _status(ui, repo, kwt, unknown, *pats, **opts):
256 256 '''Bails out if [keyword] configuration is not active.
257 257 Returns status of working directory.'''
258 258 if kwt:
259 259 matcher = cmdutil.match(repo, pats, opts)
260 260 return repo.status(match=matcher, unknown=unknown, clean=True)
261 261 if ui.configitems('keyword'):
262 262 raise util.Abort(_('[keyword] patterns cannot match'))
263 263 raise util.Abort(_('no [keyword] patterns configured'))
264 264
265 265 def _kwfwrite(ui, repo, expand, *pats, **opts):
266 266 '''Selects files and passes them to kwtemplater.overwrite.'''
267 267 if repo.dirstate.parents()[1] != nullid:
268 268 raise util.Abort(_('outstanding uncommitted merge'))
269 269 kwt = kwtools['templater']
270 270 status = _status(ui, repo, kwt, False, *pats, **opts)
271 271 modified, added, removed, deleted = status[:4]
272 272 if modified or added or removed or deleted:
273 273 raise util.Abort(_('outstanding uncommitted changes'))
274 274 wlock = lock = None
275 275 try:
276 276 wlock = repo.wlock()
277 277 lock = repo.lock()
278 278 kwt.overwrite(None, expand, status[6])
279 279 finally:
280 280 del wlock, lock
281 281
282 282
283 283 def demo(ui, repo, *args, **opts):
284 284 '''print [keywordmaps] configuration and an expansion example
285 285
286 286 Show current, custom, or default keyword template maps
287 287 and their expansion.
288 288
289 289 Extend current configuration by specifying maps as arguments
290 290 and optionally by reading from an additional hgrc file.
291 291
292 292 Override current keyword template maps with "default" option.
293 293 '''
294 294 def demostatus(stat):
295 295 ui.status(_('\n\t%s\n') % stat)
296 296
297 297 def demoitems(section, items):
298 298 ui.write('[%s]\n' % section)
299 299 for k, v in items:
300 300 ui.write('%s = %s\n' % (k, v))
301 301
302 302 msg = 'hg keyword config and expansion example'
303 303 kwstatus = 'current'
304 304 fn = 'demo.txt'
305 305 branchname = 'demobranch'
306 306 tmpdir = tempfile.mkdtemp('', 'kwdemo.')
307 307 ui.note(_('creating temporary repo at %s\n') % tmpdir)
308 308 repo = localrepo.localrepository(ui, tmpdir, True)
309 309 ui.setconfig('keyword', fn, '')
310 310 if args or opts.get('rcfile'):
311 311 kwstatus = 'custom'
312 312 if opts.get('rcfile'):
313 313 ui.readconfig(opts.get('rcfile'))
314 314 if opts.get('default'):
315 315 kwstatus = 'default'
316 316 kwmaps = kwtemplater.templates
317 317 if ui.configitems('keywordmaps'):
318 318 # override maps from optional rcfile
319 319 for k, v in kwmaps.iteritems():
320 320 ui.setconfig('keywordmaps', k, v)
321 321 elif args:
322 322 # simulate hgrc parsing
323 323 rcmaps = ['[keywordmaps]\n'] + [a + '\n' for a in args]
324 324 fp = repo.opener('hgrc', 'w')
325 325 fp.writelines(rcmaps)
326 326 fp.close()
327 327 ui.readconfig(repo.join('hgrc'))
328 328 if not opts.get('default'):
329 329 kwmaps = dict(ui.configitems('keywordmaps')) or kwtemplater.templates
330 330 uisetup(ui)
331 331 reposetup(ui, repo)
332 332 for k, v in ui.configitems('extensions'):
333 333 if k.endswith('keyword'):
334 334 extension = '%s = %s' % (k, v)
335 335 break
336 336 demostatus('config using %s keyword template maps' % kwstatus)
337 337 ui.write('[extensions]\n%s\n' % extension)
338 338 demoitems('keyword', ui.configitems('keyword'))
339 339 demoitems('keywordmaps', kwmaps.iteritems())
340 340 keywords = '$' + '$\n$'.join(kwmaps.keys()) + '$\n'
341 341 repo.wopener(fn, 'w').write(keywords)
342 342 repo.add([fn])
343 343 path = repo.wjoin(fn)
344 344 ui.note(_('\n%s keywords written to %s:\n') % (kwstatus, path))
345 345 ui.note(keywords)
346 346 ui.note('\nhg -R "%s" branch "%s"\n' % (tmpdir, branchname))
347 347 # silence branch command if not verbose
348 348 quiet = ui.quiet
349 349 ui.quiet = not ui.verbose
350 350 commands.branch(ui, repo, branchname)
351 351 ui.quiet = quiet
352 352 for name, cmd in ui.configitems('hooks'):
353 353 if name.split('.', 1)[0].find('commit') > -1:
354 354 repo.ui.setconfig('hooks', name, '')
355 355 ui.note(_('unhooked all commit hooks\n'))
356 356 ui.note('hg -R "%s" ci -m "%s"\n' % (tmpdir, msg))
357 357 repo.commit(text=msg)
358 358 format = ui.verbose and ' in %s' % path or ''
359 359 demostatus('%s keywords expanded%s' % (kwstatus, format))
360 360 ui.write(repo.wread(fn))
361 361 ui.debug(_('\nremoving temporary repo %s\n') % tmpdir)
362 362 shutil.rmtree(tmpdir, ignore_errors=True)
363 363
364 364 def expand(ui, repo, *pats, **opts):
365 365 '''expand keywords in working directory
366 366
367 367 Run after (re)enabling keyword expansion.
368 368
369 369 kwexpand refuses to run if given files contain local changes.
370 370 '''
371 371 # 3rd argument sets expansion to True
372 372 _kwfwrite(ui, repo, True, *pats, **opts)
373 373
374 374 def files(ui, repo, *pats, **opts):
375 375 '''print files currently configured for keyword expansion
376 376
377 377 Crosscheck which files in working directory are potential targets for
378 378 keyword expansion.
379 379 That is, files matched by [keyword] config patterns but not symlinks.
380 380 '''
381 381 kwt = kwtools['templater']
382 382 status = _status(ui, repo, kwt, opts.get('untracked'), *pats, **opts)
383 383 modified, added, removed, deleted, unknown, ignored, clean = status
384 384 files = util.sort(modified + added + clean + unknown)
385 385 wctx = repo[None]
386 386 kwfiles = [f for f in files if kwt.iskwfile(f, wctx.flags)]
387 387 cwd = pats and repo.getcwd() or ''
388 388 kwfstats = not opts.get('ignore') and (('K', kwfiles),) or ()
389 389 if opts.get('all') or opts.get('ignore'):
390 390 kwfstats += (('I', [f for f in files if f not in kwfiles]),)
391 391 for char, filenames in kwfstats:
392 392 format = (opts.get('all') or ui.verbose) and '%s %%s\n' % char or '%s\n'
393 393 for f in filenames:
394 394 ui.write(format % repo.pathto(f, cwd))
395 395
396 396 def shrink(ui, repo, *pats, **opts):
397 397 '''revert expanded keywords in working directory
398 398
399 399 Run before changing/disabling active keywords
400 400 or if you experience problems with "hg import" or "hg merge".
401 401
402 402 kwshrink refuses to run if given files contain local changes.
403 403 '''
404 404 # 3rd argument sets expansion to False
405 405 _kwfwrite(ui, repo, False, *pats, **opts)
406 406
407 407
408 408 def uisetup(ui):
409 409 '''Collects [keyword] config in kwtools.
410 410 Monkeypatches dispatch._parse if needed.'''
411 411
412 412 for pat, opt in ui.configitems('keyword'):
413 413 if opt != 'ignore':
414 414 kwtools['inc'].append(pat)
415 415 else:
416 416 kwtools['exc'].append(pat)
417 417
418 418 if kwtools['inc']:
419 def kwdispatch_parse(ui, args):
419 def kwdispatch_parse(orig, ui, args):
420 420 '''Monkeypatch dispatch._parse to obtain running hg command.'''
421 cmd, func, args, options, cmdoptions = dispatch_parse(ui, args)
421 cmd, func, args, options, cmdoptions = orig(ui, args)
422 422 kwtools['hgcmd'] = cmd
423 423 return cmd, func, args, options, cmdoptions
424 424
425 dispatch_parse = dispatch._parse
426 dispatch._parse = kwdispatch_parse
425 extensions.wrapfunction(dispatch, '_parse', kwdispatch_parse)
427 426
428 427 def reposetup(ui, repo):
429 428 '''Sets up repo as kwrepo for keyword substitution.
430 429 Overrides file method to return kwfilelog instead of filelog
431 430 if file matches user configuration.
432 431 Wraps commit to overwrite configured files with updated
433 432 keyword substitutions.
434 433 Monkeypatches patch and webcommands.'''
435 434
436 435 try:
437 436 if (not repo.local() or not kwtools['inc']
438 437 or kwtools['hgcmd'] in nokwcommands.split()
439 438 or '.hg' in util.splitpath(repo.root)
440 439 or repo._url.startswith('bundle:')):
441 440 return
442 441 except AttributeError:
443 442 pass
444 443
445 444 kwtools['templater'] = kwt = kwtemplater(ui, repo)
446 445
447 446 class kwrepo(repo.__class__):
448 447 def file(self, f):
449 448 if f[0] == '/':
450 449 f = f[1:]
451 450 return kwfilelog(self.sopener, kwt, f)
452 451
453 452 def wread(self, filename):
454 453 data = super(kwrepo, self).wread(filename)
455 454 return kwt.wread(filename, data)
456 455
457 456 def commit(self, files=None, text='', user=None, date=None,
458 457 match=None, force=False, force_editor=False,
459 458 p1=None, p2=None, extra={}, empty_ok=False):
460 459 wlock = lock = None
461 460 _p1 = _p2 = None
462 461 try:
463 462 wlock = self.wlock()
464 463 lock = self.lock()
465 464 # store and postpone commit hooks
466 465 commithooks = {}
467 466 for name, cmd in ui.configitems('hooks'):
468 467 if name.split('.', 1)[0] == 'commit':
469 468 commithooks[name] = cmd
470 469 ui.setconfig('hooks', name, None)
471 470 if commithooks:
472 471 # store parents for commit hook environment
473 472 if p1 is None:
474 473 _p1, _p2 = repo.dirstate.parents()
475 474 else:
476 475 _p1, _p2 = p1, p2 or nullid
477 476 _p1 = hex(_p1)
478 477 if _p2 == nullid:
479 478 _p2 = ''
480 479 else:
481 480 _p2 = hex(_p2)
482 481
483 482 n = super(kwrepo, self).commit(files, text, user, date, match,
484 483 force, force_editor, p1, p2,
485 484 extra, empty_ok)
486 485
487 486 # restore commit hooks
488 487 for name, cmd in commithooks.iteritems():
489 488 ui.setconfig('hooks', name, cmd)
490 489 if n is not None:
491 490 kwt.overwrite(n, True, None)
492 491 repo.hook('commit', node=n, parent1=_p1, parent2=_p2)
493 492 return n
494 493 finally:
495 494 del wlock, lock
496 495
497 496 # monkeypatches
498 def kwpatchfile_init(self, ui, fname, missing=False):
497 def kwpatchfile_init(orig, self, ui, fname, missing=False):
499 498 '''Monkeypatch/wrap patch.patchfile.__init__ to avoid
500 499 rejects or conflicts due to expanded keywords in working dir.'''
501 patchfile_init(self, ui, fname, missing)
500 orig(self, ui, fname, missing)
502 501 # shrink keywords read from working dir
503 502 self.lines = kwt.shrinklines(self.fname, self.lines)
504 503
505 def kw_diff(repo, node1=None, node2=None, match=None,
504 def kw_diff(orig, repo, node1=None, node2=None, match=None,
506 505 fp=None, changes=None, opts=None):
507 506 '''Monkeypatch patch.diff to avoid expansion except when
508 507 comparing against working dir.'''
509 508 if node2 is not None:
510 509 kwt.matcher = util.never
511 510 elif node1 is not None and node1 != repo['.'].node():
512 511 kwt.restrict = True
513 patch_diff(repo, node1, node2, match, fp, changes, opts)
514
515 def kwweb_annotate(web, req, tmpl):
516 '''Wraps webcommands.annotate turning off keyword expansion.'''
517 kwt.matcher = util.never
518 return webcommands_annotate(web, req, tmpl)
512 orig(repo, node1, node2, match, fp, changes, opts)
519 513
520 def kwweb_changeset(web, req, tmpl):
521 '''Wraps webcommands.changeset turning off keyword expansion.'''
514 def kwweb_skip(orig, web, req, tmpl):
515 '''Wraps webcommands.x turning off keyword expansion.'''
522 516 kwt.matcher = util.never
523 return webcommands_changeset(web, req, tmpl)
524
525 def kwweb_filediff(web, req, tmpl):
526 '''Wraps webcommands.filediff turning off keyword expansion.'''
527 kwt.matcher = util.never
528 return webcommands_filediff(web, req, tmpl)
517 return orig(web, req, tmpl)
529 518
530 519 repo.__class__ = kwrepo
531 520
532 patchfile_init = patch.patchfile.__init__
533 patch_diff = patch.diff
534 webcommands_annotate = webcommands.annotate
535 webcommands_changeset = webcommands.changeset
536 webcommands_filediff = webcommands.filediff
537
538 patch.patchfile.__init__ = kwpatchfile_init
539 patch.diff = kw_diff
540 webcommands.annotate = kwweb_annotate
541 webcommands.changeset = webcommands.rev = kwweb_changeset
542 webcommands.filediff = webcommands.diff = kwweb_filediff
543
521 extensions.wrapfunction(patch.patchfile, '__init__', kwpatchfile_init)
522 extensions.wrapfunction(patch, 'diff', kw_diff)
523 for c in 'annotate changeset rev filediff diff'.split():
524 extensions.wrapfunction(webcommands, c, kwweb_skip)
544 525
545 526 cmdtable = {
546 527 'kwdemo':
547 528 (demo,
548 529 [('d', 'default', None, _('show default keyword template maps')),
549 530 ('f', 'rcfile', [], _('read maps from rcfile'))],
550 531 _('hg kwdemo [-d] [-f RCFILE] [TEMPLATEMAP]...')),
551 532 'kwexpand': (expand, commands.walkopts,
552 533 _('hg kwexpand [OPTION]... [FILE]...')),
553 534 'kwfiles':
554 535 (files,
555 536 [('a', 'all', None, _('show keyword status flags of all files')),
556 537 ('i', 'ignore', None, _('show files excluded from expansion')),
557 538 ('u', 'untracked', None, _('additionally show untracked files')),
558 539 ] + commands.walkopts,
559 540 _('hg kwfiles [OPTION]... [FILE]...')),
560 541 'kwshrink': (shrink, commands.walkopts,
561 542 _('hg kwshrink [OPTION]... [FILE]...')),
562 543 }
@@ -1,2516 +1,2508 b''
1 1 # mq.py - patch queues for mercurial
2 2 #
3 3 # Copyright 2005, 2006 Chris Mason <mason@suse.com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7
8 8 '''patch management and development
9 9
10 10 This extension lets you work with a stack of patches in a Mercurial
11 11 repository. It manages two stacks of patches - all known patches, and
12 12 applied patches (subset of known patches).
13 13
14 14 Known patches are represented as patch files in the .hg/patches
15 15 directory. Applied patches are both patch files and changesets.
16 16
17 17 Common tasks (use "hg help command" for more details):
18 18
19 19 prepare repository to work with patches qinit
20 20 create new patch qnew
21 21 import existing patch qimport
22 22
23 23 print patch series qseries
24 24 print applied patches qapplied
25 25 print name of top applied patch qtop
26 26
27 27 add known patch to applied stack qpush
28 28 remove patch from applied stack qpop
29 29 refresh contents of top applied patch qrefresh
30 30 '''
31 31
32 32 from mercurial.i18n import _
33 33 from mercurial.node import bin, hex, short
34 34 from mercurial.repo import RepoError
35 35 from mercurial import commands, cmdutil, hg, patch, revlog, util
36 from mercurial import repair
36 from mercurial import repair, extensions
37 37 import os, sys, re, errno, urllib
38 38
39 39 commands.norepo += " qclone"
40 40
41 41 # Patch names looks like unix-file names.
42 42 # They must be joinable with queue directory and result in the patch path.
43 43 normname = util.normpath
44 44
45 45 class statusentry:
46 46 def __init__(self, rev, name=None):
47 47 if not name:
48 48 fields = rev.split(':', 1)
49 49 if len(fields) == 2:
50 50 self.rev, self.name = fields
51 51 else:
52 52 self.rev, self.name = None, None
53 53 else:
54 54 self.rev, self.name = rev, name
55 55
56 56 def __str__(self):
57 57 return self.rev + ':' + self.name
58 58
59 59 class queue:
60 60 def __init__(self, ui, path, patchdir=None):
61 61 self.basepath = path
62 62 self.path = patchdir or os.path.join(path, "patches")
63 63 self.opener = util.opener(self.path)
64 64 self.ui = ui
65 65 self.applied = []
66 66 self.full_series = []
67 67 self.applied_dirty = 0
68 68 self.series_dirty = 0
69 69 self.series_path = "series"
70 70 self.status_path = "status"
71 71 self.guards_path = "guards"
72 72 self.active_guards = None
73 73 self.guards_dirty = False
74 74 self._diffopts = None
75 75
76 76 if os.path.exists(self.join(self.series_path)):
77 77 self.full_series = self.opener(self.series_path).read().splitlines()
78 78 self.parse_series()
79 79
80 80 if os.path.exists(self.join(self.status_path)):
81 81 lines = self.opener(self.status_path).read().splitlines()
82 82 self.applied = [statusentry(l) for l in lines]
83 83
84 84 def diffopts(self):
85 85 if self._diffopts is None:
86 86 self._diffopts = patch.diffopts(self.ui)
87 87 return self._diffopts
88 88
89 89 def join(self, *p):
90 90 return os.path.join(self.path, *p)
91 91
92 92 def find_series(self, patch):
93 93 pre = re.compile("(\s*)([^#]+)")
94 94 index = 0
95 95 for l in self.full_series:
96 96 m = pre.match(l)
97 97 if m:
98 98 s = m.group(2)
99 99 s = s.rstrip()
100 100 if s == patch:
101 101 return index
102 102 index += 1
103 103 return None
104 104
105 105 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
106 106
107 107 def parse_series(self):
108 108 self.series = []
109 109 self.series_guards = []
110 110 for l in self.full_series:
111 111 h = l.find('#')
112 112 if h == -1:
113 113 patch = l
114 114 comment = ''
115 115 elif h == 0:
116 116 continue
117 117 else:
118 118 patch = l[:h]
119 119 comment = l[h:]
120 120 patch = patch.strip()
121 121 if patch:
122 122 if patch in self.series:
123 123 raise util.Abort(_('%s appears more than once in %s') %
124 124 (patch, self.join(self.series_path)))
125 125 self.series.append(patch)
126 126 self.series_guards.append(self.guard_re.findall(comment))
127 127
128 128 def check_guard(self, guard):
129 129 if not guard:
130 130 return _('guard cannot be an empty string')
131 131 bad_chars = '# \t\r\n\f'
132 132 first = guard[0]
133 133 for c in '-+':
134 134 if first == c:
135 135 return (_('guard %r starts with invalid character: %r') %
136 136 (guard, c))
137 137 for c in bad_chars:
138 138 if c in guard:
139 139 return _('invalid character in guard %r: %r') % (guard, c)
140 140
141 141 def set_active(self, guards):
142 142 for guard in guards:
143 143 bad = self.check_guard(guard)
144 144 if bad:
145 145 raise util.Abort(bad)
146 146 guards = util.sort(util.unique(guards))
147 147 self.ui.debug(_('active guards: %s\n') % ' '.join(guards))
148 148 self.active_guards = guards
149 149 self.guards_dirty = True
150 150
151 151 def active(self):
152 152 if self.active_guards is None:
153 153 self.active_guards = []
154 154 try:
155 155 guards = self.opener(self.guards_path).read().split()
156 156 except IOError, err:
157 157 if err.errno != errno.ENOENT: raise
158 158 guards = []
159 159 for i, guard in enumerate(guards):
160 160 bad = self.check_guard(guard)
161 161 if bad:
162 162 self.ui.warn('%s:%d: %s\n' %
163 163 (self.join(self.guards_path), i + 1, bad))
164 164 else:
165 165 self.active_guards.append(guard)
166 166 return self.active_guards
167 167
168 168 def set_guards(self, idx, guards):
169 169 for g in guards:
170 170 if len(g) < 2:
171 171 raise util.Abort(_('guard %r too short') % g)
172 172 if g[0] not in '-+':
173 173 raise util.Abort(_('guard %r starts with invalid char') % g)
174 174 bad = self.check_guard(g[1:])
175 175 if bad:
176 176 raise util.Abort(bad)
177 177 drop = self.guard_re.sub('', self.full_series[idx])
178 178 self.full_series[idx] = drop + ''.join([' #' + g for g in guards])
179 179 self.parse_series()
180 180 self.series_dirty = True
181 181
182 182 def pushable(self, idx):
183 183 if isinstance(idx, str):
184 184 idx = self.series.index(idx)
185 185 patchguards = self.series_guards[idx]
186 186 if not patchguards:
187 187 return True, None
188 188 default = False
189 189 guards = self.active()
190 190 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
191 191 if exactneg:
192 192 return False, exactneg[0]
193 193 pos = [g for g in patchguards if g[0] == '+']
194 194 exactpos = [g for g in pos if g[1:] in guards]
195 195 if pos:
196 196 if exactpos:
197 197 return True, exactpos[0]
198 198 return False, pos
199 199 return True, ''
200 200
201 201 def explain_pushable(self, idx, all_patches=False):
202 202 write = all_patches and self.ui.write or self.ui.warn
203 203 if all_patches or self.ui.verbose:
204 204 if isinstance(idx, str):
205 205 idx = self.series.index(idx)
206 206 pushable, why = self.pushable(idx)
207 207 if all_patches and pushable:
208 208 if why is None:
209 209 write(_('allowing %s - no guards in effect\n') %
210 210 self.series[idx])
211 211 else:
212 212 if not why:
213 213 write(_('allowing %s - no matching negative guards\n') %
214 214 self.series[idx])
215 215 else:
216 216 write(_('allowing %s - guarded by %r\n') %
217 217 (self.series[idx], why))
218 218 if not pushable:
219 219 if why:
220 220 write(_('skipping %s - guarded by %r\n') %
221 221 (self.series[idx], why))
222 222 else:
223 223 write(_('skipping %s - no matching guards\n') %
224 224 self.series[idx])
225 225
226 226 def save_dirty(self):
227 227 def write_list(items, path):
228 228 fp = self.opener(path, 'w')
229 229 for i in items:
230 230 fp.write("%s\n" % i)
231 231 fp.close()
232 232 if self.applied_dirty: write_list(map(str, self.applied), self.status_path)
233 233 if self.series_dirty: write_list(self.full_series, self.series_path)
234 234 if self.guards_dirty: write_list(self.active_guards, self.guards_path)
235 235
236 236 def readheaders(self, patch):
237 237 def eatdiff(lines):
238 238 while lines:
239 239 l = lines[-1]
240 240 if (l.startswith("diff -") or
241 241 l.startswith("Index:") or
242 242 l.startswith("===========")):
243 243 del lines[-1]
244 244 else:
245 245 break
246 246 def eatempty(lines):
247 247 while lines:
248 248 l = lines[-1]
249 249 if re.match('\s*$', l):
250 250 del lines[-1]
251 251 else:
252 252 break
253 253
254 254 pf = self.join(patch)
255 255 message = []
256 256 comments = []
257 257 user = None
258 258 date = None
259 259 format = None
260 260 subject = None
261 261 diffstart = 0
262 262
263 263 for line in file(pf):
264 264 line = line.rstrip()
265 265 if line.startswith('diff --git'):
266 266 diffstart = 2
267 267 break
268 268 if diffstart:
269 269 if line.startswith('+++ '):
270 270 diffstart = 2
271 271 break
272 272 if line.startswith("--- "):
273 273 diffstart = 1
274 274 continue
275 275 elif format == "hgpatch":
276 276 # parse values when importing the result of an hg export
277 277 if line.startswith("# User "):
278 278 user = line[7:]
279 279 elif line.startswith("# Date "):
280 280 date = line[7:]
281 281 elif not line.startswith("# ") and line:
282 282 message.append(line)
283 283 format = None
284 284 elif line == '# HG changeset patch':
285 285 format = "hgpatch"
286 286 elif (format != "tagdone" and (line.startswith("Subject: ") or
287 287 line.startswith("subject: "))):
288 288 subject = line[9:]
289 289 format = "tag"
290 290 elif (format != "tagdone" and (line.startswith("From: ") or
291 291 line.startswith("from: "))):
292 292 user = line[6:]
293 293 format = "tag"
294 294 elif format == "tag" and line == "":
295 295 # when looking for tags (subject: from: etc) they
296 296 # end once you find a blank line in the source
297 297 format = "tagdone"
298 298 elif message or line:
299 299 message.append(line)
300 300 comments.append(line)
301 301
302 302 eatdiff(message)
303 303 eatdiff(comments)
304 304 eatempty(message)
305 305 eatempty(comments)
306 306
307 307 # make sure message isn't empty
308 308 if format and format.startswith("tag") and subject:
309 309 message.insert(0, "")
310 310 message.insert(0, subject)
311 311 return (message, comments, user, date, diffstart > 1)
312 312
313 313 def removeundo(self, repo):
314 314 undo = repo.sjoin('undo')
315 315 if not os.path.exists(undo):
316 316 return
317 317 try:
318 318 os.unlink(undo)
319 319 except OSError, inst:
320 320 self.ui.warn(_('error removing undo: %s\n') % str(inst))
321 321
322 322 def printdiff(self, repo, node1, node2=None, files=None,
323 323 fp=None, changes=None, opts={}):
324 324 m = cmdutil.match(repo, files, opts)
325 325 patch.diff(repo, node1, node2, m, fp, changes, self.diffopts())
326 326
327 327 def mergeone(self, repo, mergeq, head, patch, rev):
328 328 # first try just applying the patch
329 329 (err, n) = self.apply(repo, [ patch ], update_status=False,
330 330 strict=True, merge=rev)
331 331
332 332 if err == 0:
333 333 return (err, n)
334 334
335 335 if n is None:
336 336 raise util.Abort(_("apply failed for patch %s") % patch)
337 337
338 338 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
339 339
340 340 # apply failed, strip away that rev and merge.
341 341 hg.clean(repo, head)
342 342 self.strip(repo, n, update=False, backup='strip')
343 343
344 344 ctx = repo[rev]
345 345 ret = hg.merge(repo, rev)
346 346 if ret:
347 347 raise util.Abort(_("update returned %d") % ret)
348 348 n = repo.commit(None, ctx.description(), ctx.user(), force=1)
349 349 if n == None:
350 350 raise util.Abort(_("repo commit failed"))
351 351 try:
352 352 message, comments, user, date, patchfound = mergeq.readheaders(patch)
353 353 except:
354 354 raise util.Abort(_("unable to read %s") % patch)
355 355
356 356 patchf = self.opener(patch, "w")
357 357 if comments:
358 358 comments = "\n".join(comments) + '\n\n'
359 359 patchf.write(comments)
360 360 self.printdiff(repo, head, n, fp=patchf)
361 361 patchf.close()
362 362 self.removeundo(repo)
363 363 return (0, n)
364 364
365 365 def qparents(self, repo, rev=None):
366 366 if rev is None:
367 367 (p1, p2) = repo.dirstate.parents()
368 368 if p2 == revlog.nullid:
369 369 return p1
370 370 if len(self.applied) == 0:
371 371 return None
372 372 return revlog.bin(self.applied[-1].rev)
373 373 pp = repo.changelog.parents(rev)
374 374 if pp[1] != revlog.nullid:
375 375 arevs = [ x.rev for x in self.applied ]
376 376 p0 = revlog.hex(pp[0])
377 377 p1 = revlog.hex(pp[1])
378 378 if p0 in arevs:
379 379 return pp[0]
380 380 if p1 in arevs:
381 381 return pp[1]
382 382 return pp[0]
383 383
384 384 def mergepatch(self, repo, mergeq, series):
385 385 if len(self.applied) == 0:
386 386 # each of the patches merged in will have two parents. This
387 387 # can confuse the qrefresh, qdiff, and strip code because it
388 388 # needs to know which parent is actually in the patch queue.
389 389 # so, we insert a merge marker with only one parent. This way
390 390 # the first patch in the queue is never a merge patch
391 391 #
392 392 pname = ".hg.patches.merge.marker"
393 393 n = repo.commit(None, '[mq]: merge marker', user=None, force=1)
394 394 self.removeundo(repo)
395 395 self.applied.append(statusentry(revlog.hex(n), pname))
396 396 self.applied_dirty = 1
397 397
398 398 head = self.qparents(repo)
399 399
400 400 for patch in series:
401 401 patch = mergeq.lookup(patch, strict=True)
402 402 if not patch:
403 403 self.ui.warn(_("patch %s does not exist\n") % patch)
404 404 return (1, None)
405 405 pushable, reason = self.pushable(patch)
406 406 if not pushable:
407 407 self.explain_pushable(patch, all_patches=True)
408 408 continue
409 409 info = mergeq.isapplied(patch)
410 410 if not info:
411 411 self.ui.warn(_("patch %s is not applied\n") % patch)
412 412 return (1, None)
413 413 rev = revlog.bin(info[1])
414 414 (err, head) = self.mergeone(repo, mergeq, head, patch, rev)
415 415 if head:
416 416 self.applied.append(statusentry(revlog.hex(head), patch))
417 417 self.applied_dirty = 1
418 418 if err:
419 419 return (err, head)
420 420 self.save_dirty()
421 421 return (0, head)
422 422
423 423 def patch(self, repo, patchfile):
424 424 '''Apply patchfile to the working directory.
425 425 patchfile: file name of patch'''
426 426 files = {}
427 427 try:
428 428 fuzz = patch.patch(patchfile, self.ui, strip=1, cwd=repo.root,
429 429 files=files)
430 430 except Exception, inst:
431 431 self.ui.note(str(inst) + '\n')
432 432 if not self.ui.verbose:
433 433 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
434 434 return (False, files, False)
435 435
436 436 return (True, files, fuzz)
437 437
438 438 def apply(self, repo, series, list=False, update_status=True,
439 439 strict=False, patchdir=None, merge=None, all_files={}):
440 440 wlock = lock = tr = None
441 441 try:
442 442 wlock = repo.wlock()
443 443 lock = repo.lock()
444 444 tr = repo.transaction()
445 445 try:
446 446 ret = self._apply(repo, series, list, update_status,
447 447 strict, patchdir, merge, all_files=all_files)
448 448 tr.close()
449 449 self.save_dirty()
450 450 return ret
451 451 except:
452 452 try:
453 453 tr.abort()
454 454 finally:
455 455 repo.invalidate()
456 456 repo.dirstate.invalidate()
457 457 raise
458 458 finally:
459 459 del tr, lock, wlock
460 460 self.removeundo(repo)
461 461
462 462 def _apply(self, repo, series, list=False, update_status=True,
463 463 strict=False, patchdir=None, merge=None, all_files={}):
464 464 # TODO unify with commands.py
465 465 if not patchdir:
466 466 patchdir = self.path
467 467 err = 0
468 468 n = None
469 469 for patchname in series:
470 470 pushable, reason = self.pushable(patchname)
471 471 if not pushable:
472 472 self.explain_pushable(patchname, all_patches=True)
473 473 continue
474 474 self.ui.warn(_("applying %s\n") % patchname)
475 475 pf = os.path.join(patchdir, patchname)
476 476
477 477 try:
478 478 message, comments, user, date, patchfound = self.readheaders(patchname)
479 479 except:
480 480 self.ui.warn(_("Unable to read %s\n") % patchname)
481 481 err = 1
482 482 break
483 483
484 484 if not message:
485 485 message = _("imported patch %s\n") % patchname
486 486 else:
487 487 if list:
488 488 message.append(_("\nimported patch %s") % patchname)
489 489 message = '\n'.join(message)
490 490
491 491 (patcherr, files, fuzz) = self.patch(repo, pf)
492 492 all_files.update(files)
493 493 patcherr = not patcherr
494 494
495 495 if merge and files:
496 496 # Mark as removed/merged and update dirstate parent info
497 497 removed = []
498 498 merged = []
499 499 for f in files:
500 500 if os.path.exists(repo.wjoin(f)):
501 501 merged.append(f)
502 502 else:
503 503 removed.append(f)
504 504 for f in removed:
505 505 repo.dirstate.remove(f)
506 506 for f in merged:
507 507 repo.dirstate.merge(f)
508 508 p1, p2 = repo.dirstate.parents()
509 509 repo.dirstate.setparents(p1, merge)
510 510
511 511 files = patch.updatedir(self.ui, repo, files)
512 512 match = cmdutil.matchfiles(repo, files or [])
513 513 n = repo.commit(files, message, user, date, match=match,
514 514 force=True)
515 515
516 516 if n == None:
517 517 raise util.Abort(_("repo commit failed"))
518 518
519 519 if update_status:
520 520 self.applied.append(statusentry(revlog.hex(n), patchname))
521 521
522 522 if patcherr:
523 523 if not patchfound:
524 524 self.ui.warn(_("patch %s is empty\n") % patchname)
525 525 err = 0
526 526 else:
527 527 self.ui.warn(_("patch failed, rejects left in working dir\n"))
528 528 err = 1
529 529 break
530 530
531 531 if fuzz and strict:
532 532 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
533 533 err = 1
534 534 break
535 535 return (err, n)
536 536
537 537 def _clean_series(self, patches):
538 538 indices = util.sort([self.find_series(p) for p in patches])
539 539 for i in indices[-1::-1]:
540 540 del self.full_series[i]
541 541 self.parse_series()
542 542 self.series_dirty = 1
543 543
544 544 def finish(self, repo, revs):
545 545 revs.sort()
546 546 firstrev = repo[self.applied[0].rev].rev()
547 547 appliedbase = 0
548 548 patches = []
549 549 for rev in util.sort(revs):
550 550 if rev < firstrev:
551 551 raise util.Abort(_('revision %d is not managed') % rev)
552 552 base = revlog.bin(self.applied[appliedbase].rev)
553 553 node = repo.changelog.node(rev)
554 554 if node != base:
555 555 raise util.Abort(_('cannot delete revision %d above '
556 556 'applied patches') % rev)
557 557 patches.append(self.applied[appliedbase].name)
558 558 appliedbase += 1
559 559
560 560 r = self.qrepo()
561 561 if r:
562 562 r.remove(patches, True)
563 563 else:
564 564 for p in patches:
565 565 os.unlink(self.join(p))
566 566
567 567 del self.applied[:appliedbase]
568 568 self.applied_dirty = 1
569 569 self._clean_series(patches)
570 570
571 571 def delete(self, repo, patches, opts):
572 572 if not patches and not opts.get('rev'):
573 573 raise util.Abort(_('qdelete requires at least one revision or '
574 574 'patch name'))
575 575
576 576 realpatches = []
577 577 for patch in patches:
578 578 patch = self.lookup(patch, strict=True)
579 579 info = self.isapplied(patch)
580 580 if info:
581 581 raise util.Abort(_("cannot delete applied patch %s") % patch)
582 582 if patch not in self.series:
583 583 raise util.Abort(_("patch %s not in series file") % patch)
584 584 realpatches.append(patch)
585 585
586 586 appliedbase = 0
587 587 if opts.get('rev'):
588 588 if not self.applied:
589 589 raise util.Abort(_('no patches applied'))
590 590 revs = cmdutil.revrange(repo, opts['rev'])
591 591 if len(revs) > 1 and revs[0] > revs[1]:
592 592 revs.reverse()
593 593 for rev in revs:
594 594 if appliedbase >= len(self.applied):
595 595 raise util.Abort(_("revision %d is not managed") % rev)
596 596
597 597 base = revlog.bin(self.applied[appliedbase].rev)
598 598 node = repo.changelog.node(rev)
599 599 if node != base:
600 600 raise util.Abort(_("cannot delete revision %d above "
601 601 "applied patches") % rev)
602 602 realpatches.append(self.applied[appliedbase].name)
603 603 appliedbase += 1
604 604
605 605 if not opts.get('keep'):
606 606 r = self.qrepo()
607 607 if r:
608 608 r.remove(realpatches, True)
609 609 else:
610 610 for p in realpatches:
611 611 os.unlink(self.join(p))
612 612
613 613 if appliedbase:
614 614 del self.applied[:appliedbase]
615 615 self.applied_dirty = 1
616 616 self._clean_series(realpatches)
617 617
618 618 def check_toppatch(self, repo):
619 619 if len(self.applied) > 0:
620 620 top = revlog.bin(self.applied[-1].rev)
621 621 pp = repo.dirstate.parents()
622 622 if top not in pp:
623 623 raise util.Abort(_("working directory revision is not qtip"))
624 624 return top
625 625 return None
626 626 def check_localchanges(self, repo, force=False, refresh=True):
627 627 m, a, r, d = repo.status()[:4]
628 628 if m or a or r or d:
629 629 if not force:
630 630 if refresh:
631 631 raise util.Abort(_("local changes found, refresh first"))
632 632 else:
633 633 raise util.Abort(_("local changes found"))
634 634 return m, a, r, d
635 635
636 636 _reserved = ('series', 'status', 'guards')
637 637 def check_reserved_name(self, name):
638 638 if (name in self._reserved or name.startswith('.hg')
639 639 or name.startswith('.mq')):
640 640 raise util.Abort(_('"%s" cannot be used as the name of a patch')
641 641 % name)
642 642
643 643 def new(self, repo, patchfn, *pats, **opts):
644 644 """options:
645 645 msg: a string or a no-argument function returning a string
646 646 """
647 647 msg = opts.get('msg')
648 648 force = opts.get('force')
649 649 user = opts.get('user')
650 650 date = opts.get('date')
651 651 if date:
652 652 date = util.parsedate(date)
653 653 self.check_reserved_name(patchfn)
654 654 if os.path.exists(self.join(patchfn)):
655 655 raise util.Abort(_('patch "%s" already exists') % patchfn)
656 656 if opts.get('include') or opts.get('exclude') or pats:
657 657 match = cmdutil.match(repo, pats, opts)
658 658 # detect missing files in pats
659 659 def badfn(f, msg):
660 660 raise util.Abort('%s: %s' % (f, msg))
661 661 match.bad = badfn
662 662 m, a, r, d = repo.status(match=match)[:4]
663 663 else:
664 664 m, a, r, d = self.check_localchanges(repo, force)
665 665 match = cmdutil.match(repo, m + a + r)
666 666 commitfiles = m + a + r
667 667 self.check_toppatch(repo)
668 668 insert = self.full_series_end()
669 669 wlock = repo.wlock()
670 670 try:
671 671 # if patch file write fails, abort early
672 672 p = self.opener(patchfn, "w")
673 673 try:
674 674 if date:
675 675 p.write("# HG changeset patch\n")
676 676 if user:
677 677 p.write("# User " + user + "\n")
678 678 p.write("# Date %d %d\n\n" % date)
679 679 elif user:
680 680 p.write("From: " + user + "\n\n")
681 681
682 682 if callable(msg):
683 683 msg = msg()
684 684 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
685 685 n = repo.commit(commitfiles, commitmsg, user, date, match=match, force=True)
686 686 if n == None:
687 687 raise util.Abort(_("repo commit failed"))
688 688 try:
689 689 self.full_series[insert:insert] = [patchfn]
690 690 self.applied.append(statusentry(revlog.hex(n), patchfn))
691 691 self.parse_series()
692 692 self.series_dirty = 1
693 693 self.applied_dirty = 1
694 694 if msg:
695 695 msg = msg + "\n"
696 696 p.write(msg)
697 697 if commitfiles:
698 698 diffopts = self.diffopts()
699 699 if opts.get('git'): diffopts.git = True
700 700 parent = self.qparents(repo, n)
701 701 patch.diff(repo, node1=parent, node2=n, fp=p,
702 702 match=match, opts=diffopts)
703 703 p.close()
704 704 wlock = None
705 705 r = self.qrepo()
706 706 if r: r.add([patchfn])
707 707 except:
708 708 repo.rollback()
709 709 raise
710 710 except Exception, inst:
711 711 patchpath = self.join(patchfn)
712 712 try:
713 713 os.unlink(patchpath)
714 714 except:
715 715 self.ui.warn(_('error unlinking %s\n') % patchpath)
716 716 raise
717 717 self.removeundo(repo)
718 718 finally:
719 719 del wlock
720 720
721 721 def strip(self, repo, rev, update=True, backup="all", force=None):
722 722 wlock = lock = None
723 723 try:
724 724 wlock = repo.wlock()
725 725 lock = repo.lock()
726 726
727 727 if update:
728 728 self.check_localchanges(repo, force=force, refresh=False)
729 729 urev = self.qparents(repo, rev)
730 730 hg.clean(repo, urev)
731 731 repo.dirstate.write()
732 732
733 733 self.removeundo(repo)
734 734 repair.strip(self.ui, repo, rev, backup)
735 735 # strip may have unbundled a set of backed up revisions after
736 736 # the actual strip
737 737 self.removeundo(repo)
738 738 finally:
739 739 del lock, wlock
740 740
741 741 def isapplied(self, patch):
742 742 """returns (index, rev, patch)"""
743 743 for i in xrange(len(self.applied)):
744 744 a = self.applied[i]
745 745 if a.name == patch:
746 746 return (i, a.rev, a.name)
747 747 return None
748 748
749 749 # if the exact patch name does not exist, we try a few
750 750 # variations. If strict is passed, we try only #1
751 751 #
752 752 # 1) a number to indicate an offset in the series file
753 753 # 2) a unique substring of the patch name was given
754 754 # 3) patchname[-+]num to indicate an offset in the series file
755 755 def lookup(self, patch, strict=False):
756 756 patch = patch and str(patch)
757 757
758 758 def partial_name(s):
759 759 if s in self.series:
760 760 return s
761 761 matches = [x for x in self.series if s in x]
762 762 if len(matches) > 1:
763 763 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
764 764 for m in matches:
765 765 self.ui.warn(' %s\n' % m)
766 766 return None
767 767 if matches:
768 768 return matches[0]
769 769 if len(self.series) > 0 and len(self.applied) > 0:
770 770 if s == 'qtip':
771 771 return self.series[self.series_end(True)-1]
772 772 if s == 'qbase':
773 773 return self.series[0]
774 774 return None
775 775 if patch == None:
776 776 return None
777 777
778 778 # we don't want to return a partial match until we make
779 779 # sure the file name passed in does not exist (checked below)
780 780 res = partial_name(patch)
781 781 if res and res == patch:
782 782 return res
783 783
784 784 if not os.path.isfile(self.join(patch)):
785 785 try:
786 786 sno = int(patch)
787 787 except(ValueError, OverflowError):
788 788 pass
789 789 else:
790 790 if sno < len(self.series):
791 791 return self.series[sno]
792 792 if not strict:
793 793 # return any partial match made above
794 794 if res:
795 795 return res
796 796 minus = patch.rfind('-')
797 797 if minus >= 0:
798 798 res = partial_name(patch[:minus])
799 799 if res:
800 800 i = self.series.index(res)
801 801 try:
802 802 off = int(patch[minus+1:] or 1)
803 803 except(ValueError, OverflowError):
804 804 pass
805 805 else:
806 806 if i - off >= 0:
807 807 return self.series[i - off]
808 808 plus = patch.rfind('+')
809 809 if plus >= 0:
810 810 res = partial_name(patch[:plus])
811 811 if res:
812 812 i = self.series.index(res)
813 813 try:
814 814 off = int(patch[plus+1:] or 1)
815 815 except(ValueError, OverflowError):
816 816 pass
817 817 else:
818 818 if i + off < len(self.series):
819 819 return self.series[i + off]
820 820 raise util.Abort(_("patch %s not in series") % patch)
821 821
822 822 def push(self, repo, patch=None, force=False, list=False,
823 823 mergeq=None):
824 824 wlock = repo.wlock()
825 825 if repo.dirstate.parents()[0] != repo.changelog.tip():
826 826 self.ui.status(_("(working directory not at tip)\n"))
827 827
828 828 try:
829 829 patch = self.lookup(patch)
830 830 # Suppose our series file is: A B C and the current 'top'
831 831 # patch is B. qpush C should be performed (moving forward)
832 832 # qpush B is a NOP (no change) qpush A is an error (can't
833 833 # go backwards with qpush)
834 834 if patch:
835 835 info = self.isapplied(patch)
836 836 if info:
837 837 if info[0] < len(self.applied) - 1:
838 838 raise util.Abort(
839 839 _("cannot push to a previous patch: %s") % patch)
840 840 if info[0] < len(self.series) - 1:
841 841 self.ui.warn(
842 842 _('qpush: %s is already at the top\n') % patch)
843 843 else:
844 844 self.ui.warn(_('all patches are currently applied\n'))
845 845 return
846 846
847 847 # Following the above example, starting at 'top' of B:
848 848 # qpush should be performed (pushes C), but a subsequent
849 849 # qpush without an argument is an error (nothing to
850 850 # apply). This allows a loop of "...while hg qpush..." to
851 851 # work as it detects an error when done
852 852 if self.series_end() == len(self.series):
853 853 self.ui.warn(_('patch series already fully applied\n'))
854 854 return 1
855 855 if not force:
856 856 self.check_localchanges(repo)
857 857
858 858 self.applied_dirty = 1;
859 859 start = self.series_end()
860 860 if start > 0:
861 861 self.check_toppatch(repo)
862 862 if not patch:
863 863 patch = self.series[start]
864 864 end = start + 1
865 865 else:
866 866 end = self.series.index(patch, start) + 1
867 867 s = self.series[start:end]
868 868 all_files = {}
869 869 try:
870 870 if mergeq:
871 871 ret = self.mergepatch(repo, mergeq, s)
872 872 else:
873 873 ret = self.apply(repo, s, list, all_files=all_files)
874 874 except:
875 875 self.ui.warn(_('cleaning up working directory...'))
876 876 node = repo.dirstate.parents()[0]
877 877 hg.revert(repo, node, None)
878 878 unknown = repo.status(unknown=True)[4]
879 879 # only remove unknown files that we know we touched or
880 880 # created while patching
881 881 for f in unknown:
882 882 if f in all_files:
883 883 util.unlink(repo.wjoin(f))
884 884 self.ui.warn(_('done\n'))
885 885 raise
886 886 top = self.applied[-1].name
887 887 if ret[0]:
888 888 self.ui.write(
889 889 "Errors during apply, please fix and refresh %s\n" % top)
890 890 else:
891 891 self.ui.write("Now at: %s\n" % top)
892 892 return ret[0]
893 893 finally:
894 894 del wlock
895 895
896 896 def pop(self, repo, patch=None, force=False, update=True, all=False):
897 897 def getfile(f, rev, flags):
898 898 t = repo.file(f).read(rev)
899 899 repo.wwrite(f, t, flags)
900 900
901 901 wlock = repo.wlock()
902 902 try:
903 903 if patch:
904 904 # index, rev, patch
905 905 info = self.isapplied(patch)
906 906 if not info:
907 907 patch = self.lookup(patch)
908 908 info = self.isapplied(patch)
909 909 if not info:
910 910 raise util.Abort(_("patch %s is not applied") % patch)
911 911
912 912 if len(self.applied) == 0:
913 913 # Allow qpop -a to work repeatedly,
914 914 # but not qpop without an argument
915 915 self.ui.warn(_("no patches applied\n"))
916 916 return not all
917 917
918 918 if not update:
919 919 parents = repo.dirstate.parents()
920 920 rr = [ revlog.bin(x.rev) for x in self.applied ]
921 921 for p in parents:
922 922 if p in rr:
923 923 self.ui.warn(_("qpop: forcing dirstate update\n"))
924 924 update = True
925 925
926 926 if not force and update:
927 927 self.check_localchanges(repo)
928 928
929 929 self.applied_dirty = 1;
930 930 end = len(self.applied)
931 931 if not patch:
932 932 if all:
933 933 popi = 0
934 934 else:
935 935 popi = len(self.applied) - 1
936 936 else:
937 937 popi = info[0] + 1
938 938 if popi >= end:
939 939 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
940 940 return
941 941 info = [ popi ] + [self.applied[popi].rev, self.applied[popi].name]
942 942
943 943 start = info[0]
944 944 rev = revlog.bin(info[1])
945 945
946 946 if update:
947 947 top = self.check_toppatch(repo)
948 948
949 949 if repo.changelog.heads(rev) != [revlog.bin(self.applied[-1].rev)]:
950 950 raise util.Abort(_("popping would remove a revision not "
951 951 "managed by this patch queue"))
952 952
953 953 # we know there are no local changes, so we can make a simplified
954 954 # form of hg.update.
955 955 if update:
956 956 qp = self.qparents(repo, rev)
957 957 changes = repo.changelog.read(qp)
958 958 mmap = repo.manifest.read(changes[0])
959 959 m, a, r, d = repo.status(qp, top)[:4]
960 960 if d:
961 961 raise util.Abort(_("deletions found between repo revs"))
962 962 for f in m:
963 963 getfile(f, mmap[f], mmap.flags(f))
964 964 for f in r:
965 965 getfile(f, mmap[f], mmap.flags(f))
966 966 for f in m + r:
967 967 repo.dirstate.normal(f)
968 968 for f in a:
969 969 try:
970 970 os.unlink(repo.wjoin(f))
971 971 except OSError, e:
972 972 if e.errno != errno.ENOENT:
973 973 raise
974 974 try: os.removedirs(os.path.dirname(repo.wjoin(f)))
975 975 except: pass
976 976 repo.dirstate.forget(f)
977 977 repo.dirstate.setparents(qp, revlog.nullid)
978 978 del self.applied[start:end]
979 979 self.strip(repo, rev, update=False, backup='strip')
980 980 if len(self.applied):
981 981 self.ui.write(_("Now at: %s\n") % self.applied[-1].name)
982 982 else:
983 983 self.ui.write(_("Patch queue now empty\n"))
984 984 finally:
985 985 del wlock
986 986
987 987 def diff(self, repo, pats, opts):
988 988 top = self.check_toppatch(repo)
989 989 if not top:
990 990 self.ui.write(_("No patches applied\n"))
991 991 return
992 992 qp = self.qparents(repo, top)
993 993 self._diffopts = patch.diffopts(self.ui, opts)
994 994 self.printdiff(repo, qp, files=pats, opts=opts)
995 995
996 996 def refresh(self, repo, pats=None, **opts):
997 997 if len(self.applied) == 0:
998 998 self.ui.write(_("No patches applied\n"))
999 999 return 1
1000 1000 newdate = opts.get('date')
1001 1001 if newdate:
1002 1002 newdate = '%d %d' % util.parsedate(newdate)
1003 1003 wlock = repo.wlock()
1004 1004 try:
1005 1005 self.check_toppatch(repo)
1006 1006 (top, patchfn) = (self.applied[-1].rev, self.applied[-1].name)
1007 1007 top = revlog.bin(top)
1008 1008 if repo.changelog.heads(top) != [top]:
1009 1009 raise util.Abort(_("cannot refresh a revision with children"))
1010 1010 cparents = repo.changelog.parents(top)
1011 1011 patchparent = self.qparents(repo, top)
1012 1012 message, comments, user, date, patchfound = self.readheaders(patchfn)
1013 1013
1014 1014 patchf = self.opener(patchfn, 'r+')
1015 1015
1016 1016 # if the patch was a git patch, refresh it as a git patch
1017 1017 for line in patchf:
1018 1018 if line.startswith('diff --git'):
1019 1019 self.diffopts().git = True
1020 1020 break
1021 1021
1022 1022 msg = opts.get('msg', '').rstrip()
1023 1023 if msg and comments:
1024 1024 # Remove existing message, keeping the rest of the comments
1025 1025 # fields.
1026 1026 # If comments contains 'subject: ', message will prepend
1027 1027 # the field and a blank line.
1028 1028 if message:
1029 1029 subj = 'subject: ' + message[0].lower()
1030 1030 for i in xrange(len(comments)):
1031 1031 if subj == comments[i].lower():
1032 1032 del comments[i]
1033 1033 message = message[2:]
1034 1034 break
1035 1035 ci = 0
1036 1036 for mi in xrange(len(message)):
1037 1037 while message[mi] != comments[ci]:
1038 1038 ci += 1
1039 1039 del comments[ci]
1040 1040
1041 1041 def setheaderfield(comments, prefixes, new):
1042 1042 # Update all references to a field in the patch header.
1043 1043 # If none found, add it email style.
1044 1044 res = False
1045 1045 for prefix in prefixes:
1046 1046 for i in xrange(len(comments)):
1047 1047 if comments[i].startswith(prefix):
1048 1048 comments[i] = prefix + new
1049 1049 res = True
1050 1050 break
1051 1051 return res
1052 1052
1053 1053 newuser = opts.get('user')
1054 1054 if newuser:
1055 1055 if not setheaderfield(comments, ['From: ', '# User '], newuser):
1056 1056 try:
1057 1057 patchheaderat = comments.index('# HG changeset patch')
1058 1058 comments.insert(patchheaderat + 1,'# User ' + newuser)
1059 1059 except ValueError:
1060 1060 comments = ['From: ' + newuser, ''] + comments
1061 1061 user = newuser
1062 1062
1063 1063 if newdate:
1064 1064 if setheaderfield(comments, ['# Date '], newdate):
1065 1065 date = newdate
1066 1066
1067 1067 if msg:
1068 1068 comments.append(msg)
1069 1069
1070 1070 patchf.seek(0)
1071 1071 patchf.truncate()
1072 1072
1073 1073 if comments:
1074 1074 comments = "\n".join(comments) + '\n\n'
1075 1075 patchf.write(comments)
1076 1076
1077 1077 if opts.get('git'):
1078 1078 self.diffopts().git = True
1079 1079 tip = repo.changelog.tip()
1080 1080 if top == tip:
1081 1081 # if the top of our patch queue is also the tip, there is an
1082 1082 # optimization here. We update the dirstate in place and strip
1083 1083 # off the tip commit. Then just commit the current directory
1084 1084 # tree. We can also send repo.commit the list of files
1085 1085 # changed to speed up the diff
1086 1086 #
1087 1087 # in short mode, we only diff the files included in the
1088 1088 # patch already plus specified files
1089 1089 #
1090 1090 # this should really read:
1091 1091 # mm, dd, aa, aa2 = repo.status(tip, patchparent)[:4]
1092 1092 # but we do it backwards to take advantage of manifest/chlog
1093 1093 # caching against the next repo.status call
1094 1094 #
1095 1095 mm, aa, dd, aa2 = repo.status(patchparent, tip)[:4]
1096 1096 changes = repo.changelog.read(tip)
1097 1097 man = repo.manifest.read(changes[0])
1098 1098 aaa = aa[:]
1099 1099 matchfn = cmdutil.match(repo, pats, opts)
1100 1100 if opts.get('short'):
1101 1101 # if amending a patch, we start with existing
1102 1102 # files plus specified files - unfiltered
1103 1103 match = cmdutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1104 1104 # filter with inc/exl options
1105 1105 matchfn = cmdutil.match(repo, opts=opts)
1106 1106 else:
1107 1107 match = cmdutil.matchall(repo)
1108 1108 m, a, r, d = repo.status(match=match)[:4]
1109 1109
1110 1110 # we might end up with files that were added between
1111 1111 # tip and the dirstate parent, but then changed in the
1112 1112 # local dirstate. in this case, we want them to only
1113 1113 # show up in the added section
1114 1114 for x in m:
1115 1115 if x not in aa:
1116 1116 mm.append(x)
1117 1117 # we might end up with files added by the local dirstate that
1118 1118 # were deleted by the patch. In this case, they should only
1119 1119 # show up in the changed section.
1120 1120 for x in a:
1121 1121 if x in dd:
1122 1122 del dd[dd.index(x)]
1123 1123 mm.append(x)
1124 1124 else:
1125 1125 aa.append(x)
1126 1126 # make sure any files deleted in the local dirstate
1127 1127 # are not in the add or change column of the patch
1128 1128 forget = []
1129 1129 for x in d + r:
1130 1130 if x in aa:
1131 1131 del aa[aa.index(x)]
1132 1132 forget.append(x)
1133 1133 continue
1134 1134 elif x in mm:
1135 1135 del mm[mm.index(x)]
1136 1136 dd.append(x)
1137 1137
1138 1138 m = util.unique(mm)
1139 1139 r = util.unique(dd)
1140 1140 a = util.unique(aa)
1141 1141 c = [filter(matchfn, l) for l in (m, a, r)]
1142 1142 match = cmdutil.matchfiles(repo, util.unique(c[0] + c[1] + c[2]))
1143 1143 patch.diff(repo, patchparent, match=match,
1144 1144 fp=patchf, changes=c, opts=self.diffopts())
1145 1145 patchf.close()
1146 1146
1147 1147 repo.dirstate.setparents(*cparents)
1148 1148 copies = {}
1149 1149 for dst in a:
1150 1150 src = repo.dirstate.copied(dst)
1151 1151 if src is not None:
1152 1152 copies.setdefault(src, []).append(dst)
1153 1153 repo.dirstate.add(dst)
1154 1154 # remember the copies between patchparent and tip
1155 1155 # this may be slow, so don't do it if we're not tracking copies
1156 1156 if self.diffopts().git:
1157 1157 for dst in aaa:
1158 1158 f = repo.file(dst)
1159 1159 src = f.renamed(man[dst])
1160 1160 if src:
1161 1161 copies.setdefault(src[0], []).extend(copies.get(dst, []))
1162 1162 if dst in a:
1163 1163 copies[src[0]].append(dst)
1164 1164 # we can't copy a file created by the patch itself
1165 1165 if dst in copies:
1166 1166 del copies[dst]
1167 1167 for src, dsts in copies.iteritems():
1168 1168 for dst in dsts:
1169 1169 repo.dirstate.copy(src, dst)
1170 1170 for f in r:
1171 1171 repo.dirstate.remove(f)
1172 1172 # if the patch excludes a modified file, mark that
1173 1173 # file with mtime=0 so status can see it.
1174 1174 mm = []
1175 1175 for i in xrange(len(m)-1, -1, -1):
1176 1176 if not matchfn(m[i]):
1177 1177 mm.append(m[i])
1178 1178 del m[i]
1179 1179 for f in m:
1180 1180 repo.dirstate.normal(f)
1181 1181 for f in mm:
1182 1182 repo.dirstate.normallookup(f)
1183 1183 for f in forget:
1184 1184 repo.dirstate.forget(f)
1185 1185
1186 1186 if not msg:
1187 1187 if not message:
1188 1188 message = "[mq]: %s\n" % patchfn
1189 1189 else:
1190 1190 message = "\n".join(message)
1191 1191 else:
1192 1192 message = msg
1193 1193
1194 1194 if not user:
1195 1195 user = changes[1]
1196 1196
1197 1197 self.applied.pop()
1198 1198 self.applied_dirty = 1
1199 1199 self.strip(repo, top, update=False,
1200 1200 backup='strip')
1201 1201 n = repo.commit(match.files(), message, user, date, match=match,
1202 1202 force=1)
1203 1203 self.applied.append(statusentry(revlog.hex(n), patchfn))
1204 1204 self.removeundo(repo)
1205 1205 else:
1206 1206 self.printdiff(repo, patchparent, fp=patchf)
1207 1207 patchf.close()
1208 1208 added = repo.status()[1]
1209 1209 for a in added:
1210 1210 f = repo.wjoin(a)
1211 1211 try:
1212 1212 os.unlink(f)
1213 1213 except OSError, e:
1214 1214 if e.errno != errno.ENOENT:
1215 1215 raise
1216 1216 try: os.removedirs(os.path.dirname(f))
1217 1217 except: pass
1218 1218 # forget the file copies in the dirstate
1219 1219 # push should readd the files later on
1220 1220 repo.dirstate.forget(a)
1221 1221 self.pop(repo, force=True)
1222 1222 self.push(repo, force=True)
1223 1223 finally:
1224 1224 del wlock
1225 1225
1226 1226 def init(self, repo, create=False):
1227 1227 if not create and os.path.isdir(self.path):
1228 1228 raise util.Abort(_("patch queue directory already exists"))
1229 1229 try:
1230 1230 os.mkdir(self.path)
1231 1231 except OSError, inst:
1232 1232 if inst.errno != errno.EEXIST or not create:
1233 1233 raise
1234 1234 if create:
1235 1235 return self.qrepo(create=True)
1236 1236
1237 1237 def unapplied(self, repo, patch=None):
1238 1238 if patch and patch not in self.series:
1239 1239 raise util.Abort(_("patch %s is not in series file") % patch)
1240 1240 if not patch:
1241 1241 start = self.series_end()
1242 1242 else:
1243 1243 start = self.series.index(patch) + 1
1244 1244 unapplied = []
1245 1245 for i in xrange(start, len(self.series)):
1246 1246 pushable, reason = self.pushable(i)
1247 1247 if pushable:
1248 1248 unapplied.append((i, self.series[i]))
1249 1249 self.explain_pushable(i)
1250 1250 return unapplied
1251 1251
1252 1252 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1253 1253 summary=False):
1254 1254 def displayname(patchname):
1255 1255 if summary:
1256 1256 msg = self.readheaders(patchname)[0]
1257 1257 msg = msg and ': ' + msg[0] or ': '
1258 1258 else:
1259 1259 msg = ''
1260 1260 return '%s%s' % (patchname, msg)
1261 1261
1262 1262 applied = dict.fromkeys([p.name for p in self.applied])
1263 1263 if length is None:
1264 1264 length = len(self.series) - start
1265 1265 if not missing:
1266 1266 for i in xrange(start, start+length):
1267 1267 patch = self.series[i]
1268 1268 if patch in applied:
1269 1269 stat = 'A'
1270 1270 elif self.pushable(i)[0]:
1271 1271 stat = 'U'
1272 1272 else:
1273 1273 stat = 'G'
1274 1274 pfx = ''
1275 1275 if self.ui.verbose:
1276 1276 pfx = '%d %s ' % (i, stat)
1277 1277 elif status and status != stat:
1278 1278 continue
1279 1279 self.ui.write('%s%s\n' % (pfx, displayname(patch)))
1280 1280 else:
1281 1281 msng_list = []
1282 1282 for root, dirs, files in os.walk(self.path):
1283 1283 d = root[len(self.path) + 1:]
1284 1284 for f in files:
1285 1285 fl = os.path.join(d, f)
1286 1286 if (fl not in self.series and
1287 1287 fl not in (self.status_path, self.series_path,
1288 1288 self.guards_path)
1289 1289 and not fl.startswith('.')):
1290 1290 msng_list.append(fl)
1291 1291 for x in util.sort(msng_list):
1292 1292 pfx = self.ui.verbose and ('D ') or ''
1293 1293 self.ui.write("%s%s\n" % (pfx, displayname(x)))
1294 1294
1295 1295 def issaveline(self, l):
1296 1296 if l.name == '.hg.patches.save.line':
1297 1297 return True
1298 1298
1299 1299 def qrepo(self, create=False):
1300 1300 if create or os.path.isdir(self.join(".hg")):
1301 1301 return hg.repository(self.ui, path=self.path, create=create)
1302 1302
1303 1303 def restore(self, repo, rev, delete=None, qupdate=None):
1304 1304 c = repo.changelog.read(rev)
1305 1305 desc = c[4].strip()
1306 1306 lines = desc.splitlines()
1307 1307 i = 0
1308 1308 datastart = None
1309 1309 series = []
1310 1310 applied = []
1311 1311 qpp = None
1312 1312 for i in xrange(0, len(lines)):
1313 1313 if lines[i] == 'Patch Data:':
1314 1314 datastart = i + 1
1315 1315 elif lines[i].startswith('Dirstate:'):
1316 1316 l = lines[i].rstrip()
1317 1317 l = l[10:].split(' ')
1318 1318 qpp = [ bin(x) for x in l ]
1319 1319 elif datastart != None:
1320 1320 l = lines[i].rstrip()
1321 1321 se = statusentry(l)
1322 1322 file_ = se.name
1323 1323 if se.rev:
1324 1324 applied.append(se)
1325 1325 else:
1326 1326 series.append(file_)
1327 1327 if datastart == None:
1328 1328 self.ui.warn(_("No saved patch data found\n"))
1329 1329 return 1
1330 1330 self.ui.warn(_("restoring status: %s\n") % lines[0])
1331 1331 self.full_series = series
1332 1332 self.applied = applied
1333 1333 self.parse_series()
1334 1334 self.series_dirty = 1
1335 1335 self.applied_dirty = 1
1336 1336 heads = repo.changelog.heads()
1337 1337 if delete:
1338 1338 if rev not in heads:
1339 1339 self.ui.warn(_("save entry has children, leaving it alone\n"))
1340 1340 else:
1341 1341 self.ui.warn(_("removing save entry %s\n") % short(rev))
1342 1342 pp = repo.dirstate.parents()
1343 1343 if rev in pp:
1344 1344 update = True
1345 1345 else:
1346 1346 update = False
1347 1347 self.strip(repo, rev, update=update, backup='strip')
1348 1348 if qpp:
1349 1349 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1350 1350 (short(qpp[0]), short(qpp[1])))
1351 1351 if qupdate:
1352 1352 self.ui.status(_("queue directory updating\n"))
1353 1353 r = self.qrepo()
1354 1354 if not r:
1355 1355 self.ui.warn(_("Unable to load queue repository\n"))
1356 1356 return 1
1357 1357 hg.clean(r, qpp[0])
1358 1358
1359 1359 def save(self, repo, msg=None):
1360 1360 if len(self.applied) == 0:
1361 1361 self.ui.warn(_("save: no patches applied, exiting\n"))
1362 1362 return 1
1363 1363 if self.issaveline(self.applied[-1]):
1364 1364 self.ui.warn(_("status is already saved\n"))
1365 1365 return 1
1366 1366
1367 1367 ar = [ ':' + x for x in self.full_series ]
1368 1368 if not msg:
1369 1369 msg = _("hg patches saved state")
1370 1370 else:
1371 1371 msg = "hg patches: " + msg.rstrip('\r\n')
1372 1372 r = self.qrepo()
1373 1373 if r:
1374 1374 pp = r.dirstate.parents()
1375 1375 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1376 1376 msg += "\n\nPatch Data:\n"
1377 1377 text = msg + "\n".join([str(x) for x in self.applied]) + '\n' + (ar and
1378 1378 "\n".join(ar) + '\n' or "")
1379 1379 n = repo.commit(None, text, user=None, force=1)
1380 1380 if not n:
1381 1381 self.ui.warn(_("repo commit failed\n"))
1382 1382 return 1
1383 1383 self.applied.append(statusentry(revlog.hex(n),'.hg.patches.save.line'))
1384 1384 self.applied_dirty = 1
1385 1385 self.removeundo(repo)
1386 1386
1387 1387 def full_series_end(self):
1388 1388 if len(self.applied) > 0:
1389 1389 p = self.applied[-1].name
1390 1390 end = self.find_series(p)
1391 1391 if end == None:
1392 1392 return len(self.full_series)
1393 1393 return end + 1
1394 1394 return 0
1395 1395
1396 1396 def series_end(self, all_patches=False):
1397 1397 """If all_patches is False, return the index of the next pushable patch
1398 1398 in the series, or the series length. If all_patches is True, return the
1399 1399 index of the first patch past the last applied one.
1400 1400 """
1401 1401 end = 0
1402 1402 def next(start):
1403 1403 if all_patches:
1404 1404 return start
1405 1405 i = start
1406 1406 while i < len(self.series):
1407 1407 p, reason = self.pushable(i)
1408 1408 if p:
1409 1409 break
1410 1410 self.explain_pushable(i)
1411 1411 i += 1
1412 1412 return i
1413 1413 if len(self.applied) > 0:
1414 1414 p = self.applied[-1].name
1415 1415 try:
1416 1416 end = self.series.index(p)
1417 1417 except ValueError:
1418 1418 return 0
1419 1419 return next(end + 1)
1420 1420 return next(end)
1421 1421
1422 1422 def appliedname(self, index):
1423 1423 pname = self.applied[index].name
1424 1424 if not self.ui.verbose:
1425 1425 p = pname
1426 1426 else:
1427 1427 p = str(self.series.index(pname)) + " " + pname
1428 1428 return p
1429 1429
1430 1430 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1431 1431 force=None, git=False):
1432 1432 def checkseries(patchname):
1433 1433 if patchname in self.series:
1434 1434 raise util.Abort(_('patch %s is already in the series file')
1435 1435 % patchname)
1436 1436 def checkfile(patchname):
1437 1437 if not force and os.path.exists(self.join(patchname)):
1438 1438 raise util.Abort(_('patch "%s" already exists')
1439 1439 % patchname)
1440 1440
1441 1441 if rev:
1442 1442 if files:
1443 1443 raise util.Abort(_('option "-r" not valid when importing '
1444 1444 'files'))
1445 1445 rev = cmdutil.revrange(repo, rev)
1446 1446 rev.sort(lambda x, y: cmp(y, x))
1447 1447 if (len(files) > 1 or len(rev) > 1) and patchname:
1448 1448 raise util.Abort(_('option "-n" not valid when importing multiple '
1449 1449 'patches'))
1450 1450 i = 0
1451 1451 added = []
1452 1452 if rev:
1453 1453 # If mq patches are applied, we can only import revisions
1454 1454 # that form a linear path to qbase.
1455 1455 # Otherwise, they should form a linear path to a head.
1456 1456 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1457 1457 if len(heads) > 1:
1458 1458 raise util.Abort(_('revision %d is the root of more than one '
1459 1459 'branch') % rev[-1])
1460 1460 if self.applied:
1461 1461 base = revlog.hex(repo.changelog.node(rev[0]))
1462 1462 if base in [n.rev for n in self.applied]:
1463 1463 raise util.Abort(_('revision %d is already managed')
1464 1464 % rev[0])
1465 1465 if heads != [revlog.bin(self.applied[-1].rev)]:
1466 1466 raise util.Abort(_('revision %d is not the parent of '
1467 1467 'the queue') % rev[0])
1468 1468 base = repo.changelog.rev(revlog.bin(self.applied[0].rev))
1469 1469 lastparent = repo.changelog.parentrevs(base)[0]
1470 1470 else:
1471 1471 if heads != [repo.changelog.node(rev[0])]:
1472 1472 raise util.Abort(_('revision %d has unmanaged children')
1473 1473 % rev[0])
1474 1474 lastparent = None
1475 1475
1476 1476 if git:
1477 1477 self.diffopts().git = True
1478 1478
1479 1479 for r in rev:
1480 1480 p1, p2 = repo.changelog.parentrevs(r)
1481 1481 n = repo.changelog.node(r)
1482 1482 if p2 != revlog.nullrev:
1483 1483 raise util.Abort(_('cannot import merge revision %d') % r)
1484 1484 if lastparent and lastparent != r:
1485 1485 raise util.Abort(_('revision %d is not the parent of %d')
1486 1486 % (r, lastparent))
1487 1487 lastparent = p1
1488 1488
1489 1489 if not patchname:
1490 1490 patchname = normname('%d.diff' % r)
1491 1491 self.check_reserved_name(patchname)
1492 1492 checkseries(patchname)
1493 1493 checkfile(patchname)
1494 1494 self.full_series.insert(0, patchname)
1495 1495
1496 1496 patchf = self.opener(patchname, "w")
1497 1497 patch.export(repo, [n], fp=patchf, opts=self.diffopts())
1498 1498 patchf.close()
1499 1499
1500 1500 se = statusentry(revlog.hex(n), patchname)
1501 1501 self.applied.insert(0, se)
1502 1502
1503 1503 added.append(patchname)
1504 1504 patchname = None
1505 1505 self.parse_series()
1506 1506 self.applied_dirty = 1
1507 1507
1508 1508 for filename in files:
1509 1509 if existing:
1510 1510 if filename == '-':
1511 1511 raise util.Abort(_('-e is incompatible with import from -'))
1512 1512 if not patchname:
1513 1513 patchname = normname(filename)
1514 1514 self.check_reserved_name(patchname)
1515 1515 if not os.path.isfile(self.join(patchname)):
1516 1516 raise util.Abort(_("patch %s does not exist") % patchname)
1517 1517 else:
1518 1518 try:
1519 1519 if filename == '-':
1520 1520 if not patchname:
1521 1521 raise util.Abort(_('need --name to import a patch from -'))
1522 1522 text = sys.stdin.read()
1523 1523 else:
1524 1524 if os.path.exists(filename):
1525 1525 text = file(filename, 'rb').read()
1526 1526 else:
1527 1527 text = urllib.urlopen(filename).read()
1528 1528 except IOError:
1529 1529 raise util.Abort(_("unable to read %s") % filename)
1530 1530 if not patchname:
1531 1531 patchname = normname(os.path.basename(filename))
1532 1532 self.check_reserved_name(patchname)
1533 1533 checkfile(patchname)
1534 1534 patchf = self.opener(patchname, "w")
1535 1535 patchf.write(text)
1536 1536 if not force:
1537 1537 checkseries(patchname)
1538 1538 if patchname not in self.series:
1539 1539 index = self.full_series_end() + i
1540 1540 self.full_series[index:index] = [patchname]
1541 1541 self.parse_series()
1542 1542 self.ui.warn("adding %s to series file\n" % patchname)
1543 1543 i += 1
1544 1544 added.append(patchname)
1545 1545 patchname = None
1546 1546 self.series_dirty = 1
1547 1547 qrepo = self.qrepo()
1548 1548 if qrepo:
1549 1549 qrepo.add(added)
1550 1550
1551 1551 def delete(ui, repo, *patches, **opts):
1552 1552 """remove patches from queue
1553 1553
1554 1554 The patches must not be applied, unless they are arguments to
1555 1555 the --rev parameter. At least one patch or revision is required.
1556 1556
1557 1557 With --rev, mq will stop managing the named revisions (converting
1558 1558 them to regular mercurial changesets). The qfinish command should be
1559 1559 used as an alternative for qdel -r, as the latter option is deprecated.
1560 1560
1561 1561 With --keep, the patch files are preserved in the patch directory."""
1562 1562 q = repo.mq
1563 1563 q.delete(repo, patches, opts)
1564 1564 q.save_dirty()
1565 1565 return 0
1566 1566
1567 1567 def applied(ui, repo, patch=None, **opts):
1568 1568 """print the patches already applied"""
1569 1569 q = repo.mq
1570 1570 if patch:
1571 1571 if patch not in q.series:
1572 1572 raise util.Abort(_("patch %s is not in series file") % patch)
1573 1573 end = q.series.index(patch) + 1
1574 1574 else:
1575 1575 end = q.series_end(True)
1576 1576 return q.qseries(repo, length=end, status='A', summary=opts.get('summary'))
1577 1577
1578 1578 def unapplied(ui, repo, patch=None, **opts):
1579 1579 """print the patches not yet applied"""
1580 1580 q = repo.mq
1581 1581 if patch:
1582 1582 if patch not in q.series:
1583 1583 raise util.Abort(_("patch %s is not in series file") % patch)
1584 1584 start = q.series.index(patch) + 1
1585 1585 else:
1586 1586 start = q.series_end(True)
1587 1587 q.qseries(repo, start=start, status='U', summary=opts.get('summary'))
1588 1588
1589 1589 def qimport(ui, repo, *filename, **opts):
1590 1590 """import a patch
1591 1591
1592 1592 The patch is inserted into the series after the last applied patch.
1593 1593 If no patches have been applied, qimport prepends the patch
1594 1594 to the series.
1595 1595
1596 1596 The patch will have the same name as its source file unless you
1597 1597 give it a new one with --name.
1598 1598
1599 1599 You can register an existing patch inside the patch directory
1600 1600 with the --existing flag.
1601 1601
1602 1602 With --force, an existing patch of the same name will be overwritten.
1603 1603
1604 1604 An existing changeset may be placed under mq control with --rev
1605 1605 (e.g. qimport --rev tip -n patch will place tip under mq control).
1606 1606 With --git, patches imported with --rev will use the git diff
1607 1607 format.
1608 1608 """
1609 1609 q = repo.mq
1610 1610 q.qimport(repo, filename, patchname=opts['name'],
1611 1611 existing=opts['existing'], force=opts['force'], rev=opts['rev'],
1612 1612 git=opts['git'])
1613 1613 q.save_dirty()
1614 1614 return 0
1615 1615
1616 1616 def init(ui, repo, **opts):
1617 1617 """init a new queue repository
1618 1618
1619 1619 The queue repository is unversioned by default. If -c is
1620 1620 specified, qinit will create a separate nested repository
1621 1621 for patches (qinit -c may also be run later to convert
1622 1622 an unversioned patch repository into a versioned one).
1623 1623 You can use qcommit to commit changes to this queue repository."""
1624 1624 q = repo.mq
1625 1625 r = q.init(repo, create=opts['create_repo'])
1626 1626 q.save_dirty()
1627 1627 if r:
1628 1628 if not os.path.exists(r.wjoin('.hgignore')):
1629 1629 fp = r.wopener('.hgignore', 'w')
1630 1630 fp.write('^\\.hg\n')
1631 1631 fp.write('^\\.mq\n')
1632 1632 fp.write('syntax: glob\n')
1633 1633 fp.write('status\n')
1634 1634 fp.write('guards\n')
1635 1635 fp.close()
1636 1636 if not os.path.exists(r.wjoin('series')):
1637 1637 r.wopener('series', 'w').close()
1638 1638 r.add(['.hgignore', 'series'])
1639 1639 commands.add(ui, r)
1640 1640 return 0
1641 1641
1642 1642 def clone(ui, source, dest=None, **opts):
1643 1643 '''clone main and patch repository at same time
1644 1644
1645 1645 If source is local, destination will have no patches applied. If
1646 1646 source is remote, this command can not check if patches are
1647 1647 applied in source, so cannot guarantee that patches are not
1648 1648 applied in destination. If you clone remote repository, be sure
1649 1649 before that it has no patches applied.
1650 1650
1651 1651 Source patch repository is looked for in <src>/.hg/patches by
1652 1652 default. Use -p <url> to change.
1653 1653
1654 1654 The patch directory must be a nested mercurial repository, as
1655 1655 would be created by qinit -c.
1656 1656 '''
1657 1657 def patchdir(repo):
1658 1658 url = repo.url()
1659 1659 if url.endswith('/'):
1660 1660 url = url[:-1]
1661 1661 return url + '/.hg/patches'
1662 1662 cmdutil.setremoteconfig(ui, opts)
1663 1663 if dest is None:
1664 1664 dest = hg.defaultdest(source)
1665 1665 sr = hg.repository(ui, ui.expandpath(source))
1666 1666 patchespath = opts['patches'] or patchdir(sr)
1667 1667 try:
1668 1668 pr = hg.repository(ui, patchespath)
1669 1669 except RepoError:
1670 1670 raise util.Abort(_('versioned patch repository not found'
1671 1671 ' (see qinit -c)'))
1672 1672 qbase, destrev = None, None
1673 1673 if sr.local():
1674 1674 if sr.mq.applied:
1675 1675 qbase = revlog.bin(sr.mq.applied[0].rev)
1676 1676 if not hg.islocal(dest):
1677 1677 heads = dict.fromkeys(sr.heads())
1678 1678 for h in sr.heads(qbase):
1679 1679 del heads[h]
1680 1680 destrev = heads.keys()
1681 1681 destrev.append(sr.changelog.parents(qbase)[0])
1682 1682 elif sr.capable('lookup'):
1683 1683 try:
1684 1684 qbase = sr.lookup('qbase')
1685 1685 except RepoError:
1686 1686 pass
1687 1687 ui.note(_('cloning main repo\n'))
1688 1688 sr, dr = hg.clone(ui, sr.url(), dest,
1689 1689 pull=opts['pull'],
1690 1690 rev=destrev,
1691 1691 update=False,
1692 1692 stream=opts['uncompressed'])
1693 1693 ui.note(_('cloning patch repo\n'))
1694 1694 spr, dpr = hg.clone(ui, opts['patches'] or patchdir(sr), patchdir(dr),
1695 1695 pull=opts['pull'], update=not opts['noupdate'],
1696 1696 stream=opts['uncompressed'])
1697 1697 if dr.local():
1698 1698 if qbase:
1699 1699 ui.note(_('stripping applied patches from destination repo\n'))
1700 1700 dr.mq.strip(dr, qbase, update=False, backup=None)
1701 1701 if not opts['noupdate']:
1702 1702 ui.note(_('updating destination repo\n'))
1703 1703 hg.update(dr, dr.changelog.tip())
1704 1704
1705 1705 def commit(ui, repo, *pats, **opts):
1706 1706 """commit changes in the queue repository"""
1707 1707 q = repo.mq
1708 1708 r = q.qrepo()
1709 1709 if not r: raise util.Abort('no queue repository')
1710 1710 commands.commit(r.ui, r, *pats, **opts)
1711 1711
1712 1712 def series(ui, repo, **opts):
1713 1713 """print the entire series file"""
1714 1714 repo.mq.qseries(repo, missing=opts['missing'], summary=opts['summary'])
1715 1715 return 0
1716 1716
1717 1717 def top(ui, repo, **opts):
1718 1718 """print the name of the current patch"""
1719 1719 q = repo.mq
1720 1720 t = q.applied and q.series_end(True) or 0
1721 1721 if t:
1722 1722 return q.qseries(repo, start=t-1, length=1, status='A',
1723 1723 summary=opts.get('summary'))
1724 1724 else:
1725 1725 ui.write("No patches applied\n")
1726 1726 return 1
1727 1727
1728 1728 def next(ui, repo, **opts):
1729 1729 """print the name of the next patch"""
1730 1730 q = repo.mq
1731 1731 end = q.series_end()
1732 1732 if end == len(q.series):
1733 1733 ui.write("All patches applied\n")
1734 1734 return 1
1735 1735 return q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
1736 1736
1737 1737 def prev(ui, repo, **opts):
1738 1738 """print the name of the previous patch"""
1739 1739 q = repo.mq
1740 1740 l = len(q.applied)
1741 1741 if l == 1:
1742 1742 ui.write("Only one patch applied\n")
1743 1743 return 1
1744 1744 if not l:
1745 1745 ui.write("No patches applied\n")
1746 1746 return 1
1747 1747 return q.qseries(repo, start=l-2, length=1, status='A',
1748 1748 summary=opts.get('summary'))
1749 1749
1750 1750 def setupheaderopts(ui, opts):
1751 1751 def do(opt,val):
1752 1752 if not opts[opt] and opts['current' + opt]:
1753 1753 opts[opt] = val
1754 1754 do('user', ui.username())
1755 1755 do('date', "%d %d" % util.makedate())
1756 1756
1757 1757 def new(ui, repo, patch, *args, **opts):
1758 1758 """create a new patch
1759 1759
1760 1760 qnew creates a new patch on top of the currently-applied patch
1761 1761 (if any). It will refuse to run if there are any outstanding
1762 1762 changes unless -f is specified, in which case the patch will
1763 1763 be initialised with them. You may also use -I, -X, and/or a list of
1764 1764 files after the patch name to add only changes to matching files
1765 1765 to the new patch, leaving the rest as uncommitted modifications.
1766 1766
1767 1767 -e, -m or -l set the patch header as well as the commit message.
1768 1768 If none is specified, the patch header is empty and the
1769 1769 commit message is '[mq]: PATCH'"""
1770 1770 msg = cmdutil.logmessage(opts)
1771 1771 def getmsg(): return ui.edit(msg, ui.username())
1772 1772 q = repo.mq
1773 1773 opts['msg'] = msg
1774 1774 if opts.get('edit'):
1775 1775 opts['msg'] = getmsg
1776 1776 else:
1777 1777 opts['msg'] = msg
1778 1778 setupheaderopts(ui, opts)
1779 1779 q.new(repo, patch, *args, **opts)
1780 1780 q.save_dirty()
1781 1781 return 0
1782 1782
1783 1783 def refresh(ui, repo, *pats, **opts):
1784 1784 """update the current patch
1785 1785
1786 1786 If any file patterns are provided, the refreshed patch will contain only
1787 1787 the modifications that match those patterns; the remaining modifications
1788 1788 will remain in the working directory.
1789 1789
1790 1790 If --short is specified, files currently included in the patch will
1791 1791 be refreshed just like matched files and remain in the patch.
1792 1792
1793 1793 hg add/remove/copy/rename work as usual, though you might want to use
1794 1794 git-style patches (--git or [diff] git=1) to track copies and renames.
1795 1795 """
1796 1796 q = repo.mq
1797 1797 message = cmdutil.logmessage(opts)
1798 1798 if opts['edit']:
1799 1799 if not q.applied:
1800 1800 ui.write(_("No patches applied\n"))
1801 1801 return 1
1802 1802 if message:
1803 1803 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
1804 1804 patch = q.applied[-1].name
1805 1805 (message, comment, user, date, hasdiff) = q.readheaders(patch)
1806 1806 message = ui.edit('\n'.join(message), user or ui.username())
1807 1807 setupheaderopts(ui, opts)
1808 1808 ret = q.refresh(repo, pats, msg=message, **opts)
1809 1809 q.save_dirty()
1810 1810 return ret
1811 1811
1812 1812 def diff(ui, repo, *pats, **opts):
1813 1813 """diff of the current patch and subsequent modifications
1814 1814
1815 1815 Shows a diff which includes the current patch as well as any changes which
1816 1816 have been made in the working directory since the last refresh (thus
1817 1817 showing what the current patch would become after a qrefresh).
1818 1818
1819 1819 Use 'hg diff' if you only want to see the changes made since the last
1820 1820 qrefresh, or 'hg export qtip' if you want to see changes made by the
1821 1821 current patch without including changes made since the qrefresh.
1822 1822 """
1823 1823 repo.mq.diff(repo, pats, opts)
1824 1824 return 0
1825 1825
1826 1826 def fold(ui, repo, *files, **opts):
1827 1827 """fold the named patches into the current patch
1828 1828
1829 1829 Patches must not yet be applied. Each patch will be successively
1830 1830 applied to the current patch in the order given. If all the
1831 1831 patches apply successfully, the current patch will be refreshed
1832 1832 with the new cumulative patch, and the folded patches will
1833 1833 be deleted. With -k/--keep, the folded patch files will not
1834 1834 be removed afterwards.
1835 1835
1836 1836 The header for each folded patch will be concatenated with
1837 1837 the current patch header, separated by a line of '* * *'."""
1838 1838
1839 1839 q = repo.mq
1840 1840
1841 1841 if not files:
1842 1842 raise util.Abort(_('qfold requires at least one patch name'))
1843 1843 if not q.check_toppatch(repo):
1844 1844 raise util.Abort(_('No patches applied'))
1845 1845
1846 1846 message = cmdutil.logmessage(opts)
1847 1847 if opts['edit']:
1848 1848 if message:
1849 1849 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
1850 1850
1851 1851 parent = q.lookup('qtip')
1852 1852 patches = []
1853 1853 messages = []
1854 1854 for f in files:
1855 1855 p = q.lookup(f)
1856 1856 if p in patches or p == parent:
1857 1857 ui.warn(_('Skipping already folded patch %s') % p)
1858 1858 if q.isapplied(p):
1859 1859 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
1860 1860 patches.append(p)
1861 1861
1862 1862 for p in patches:
1863 1863 if not message:
1864 1864 messages.append(q.readheaders(p)[0])
1865 1865 pf = q.join(p)
1866 1866 (patchsuccess, files, fuzz) = q.patch(repo, pf)
1867 1867 if not patchsuccess:
1868 1868 raise util.Abort(_('Error folding patch %s') % p)
1869 1869 patch.updatedir(ui, repo, files)
1870 1870
1871 1871 if not message:
1872 1872 message, comments, user = q.readheaders(parent)[0:3]
1873 1873 for msg in messages:
1874 1874 message.append('* * *')
1875 1875 message.extend(msg)
1876 1876 message = '\n'.join(message)
1877 1877
1878 1878 if opts['edit']:
1879 1879 message = ui.edit(message, user or ui.username())
1880 1880
1881 1881 q.refresh(repo, msg=message)
1882 1882 q.delete(repo, patches, opts)
1883 1883 q.save_dirty()
1884 1884
1885 1885 def goto(ui, repo, patch, **opts):
1886 1886 '''push or pop patches until named patch is at top of stack'''
1887 1887 q = repo.mq
1888 1888 patch = q.lookup(patch)
1889 1889 if q.isapplied(patch):
1890 1890 ret = q.pop(repo, patch, force=opts['force'])
1891 1891 else:
1892 1892 ret = q.push(repo, patch, force=opts['force'])
1893 1893 q.save_dirty()
1894 1894 return ret
1895 1895
1896 1896 def guard(ui, repo, *args, **opts):
1897 1897 '''set or print guards for a patch
1898 1898
1899 1899 Guards control whether a patch can be pushed. A patch with no
1900 1900 guards is always pushed. A patch with a positive guard ("+foo") is
1901 1901 pushed only if the qselect command has activated it. A patch with
1902 1902 a negative guard ("-foo") is never pushed if the qselect command
1903 1903 has activated it.
1904 1904
1905 1905 With no arguments, print the currently active guards.
1906 1906 With arguments, set guards for the named patch.
1907 1907
1908 1908 To set a negative guard "-foo" on topmost patch ("--" is needed so
1909 1909 hg will not interpret "-foo" as an option):
1910 1910 hg qguard -- -foo
1911 1911
1912 1912 To set guards on another patch:
1913 1913 hg qguard other.patch +2.6.17 -stable
1914 1914 '''
1915 1915 def status(idx):
1916 1916 guards = q.series_guards[idx] or ['unguarded']
1917 1917 ui.write('%s: %s\n' % (q.series[idx], ' '.join(guards)))
1918 1918 q = repo.mq
1919 1919 patch = None
1920 1920 args = list(args)
1921 1921 if opts['list']:
1922 1922 if args or opts['none']:
1923 1923 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
1924 1924 for i in xrange(len(q.series)):
1925 1925 status(i)
1926 1926 return
1927 1927 if not args or args[0][0:1] in '-+':
1928 1928 if not q.applied:
1929 1929 raise util.Abort(_('no patches applied'))
1930 1930 patch = q.applied[-1].name
1931 1931 if patch is None and args[0][0:1] not in '-+':
1932 1932 patch = args.pop(0)
1933 1933 if patch is None:
1934 1934 raise util.Abort(_('no patch to work with'))
1935 1935 if args or opts['none']:
1936 1936 idx = q.find_series(patch)
1937 1937 if idx is None:
1938 1938 raise util.Abort(_('no patch named %s') % patch)
1939 1939 q.set_guards(idx, args)
1940 1940 q.save_dirty()
1941 1941 else:
1942 1942 status(q.series.index(q.lookup(patch)))
1943 1943
1944 1944 def header(ui, repo, patch=None):
1945 1945 """Print the header of the topmost or specified patch"""
1946 1946 q = repo.mq
1947 1947
1948 1948 if patch:
1949 1949 patch = q.lookup(patch)
1950 1950 else:
1951 1951 if not q.applied:
1952 1952 ui.write('No patches applied\n')
1953 1953 return 1
1954 1954 patch = q.lookup('qtip')
1955 1955 message = repo.mq.readheaders(patch)[0]
1956 1956
1957 1957 ui.write('\n'.join(message) + '\n')
1958 1958
1959 1959 def lastsavename(path):
1960 1960 (directory, base) = os.path.split(path)
1961 1961 names = os.listdir(directory)
1962 1962 namere = re.compile("%s.([0-9]+)" % base)
1963 1963 maxindex = None
1964 1964 maxname = None
1965 1965 for f in names:
1966 1966 m = namere.match(f)
1967 1967 if m:
1968 1968 index = int(m.group(1))
1969 1969 if maxindex == None or index > maxindex:
1970 1970 maxindex = index
1971 1971 maxname = f
1972 1972 if maxname:
1973 1973 return (os.path.join(directory, maxname), maxindex)
1974 1974 return (None, None)
1975 1975
1976 1976 def savename(path):
1977 1977 (last, index) = lastsavename(path)
1978 1978 if last is None:
1979 1979 index = 0
1980 1980 newpath = path + ".%d" % (index + 1)
1981 1981 return newpath
1982 1982
1983 1983 def push(ui, repo, patch=None, **opts):
1984 1984 """push the next patch onto the stack
1985 1985
1986 1986 When --force is applied, all local changes in patched files will be lost.
1987 1987 """
1988 1988 q = repo.mq
1989 1989 mergeq = None
1990 1990
1991 1991 if opts['all']:
1992 1992 if not q.series:
1993 1993 ui.warn(_('no patches in series\n'))
1994 1994 return 0
1995 1995 patch = q.series[-1]
1996 1996 if opts['merge']:
1997 1997 if opts['name']:
1998 1998 newpath = repo.join(opts['name'])
1999 1999 else:
2000 2000 newpath, i = lastsavename(q.path)
2001 2001 if not newpath:
2002 2002 ui.warn(_("no saved queues found, please use -n\n"))
2003 2003 return 1
2004 2004 mergeq = queue(ui, repo.join(""), newpath)
2005 2005 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2006 2006 ret = q.push(repo, patch, force=opts['force'], list=opts['list'],
2007 2007 mergeq=mergeq)
2008 2008 return ret
2009 2009
2010 2010 def pop(ui, repo, patch=None, **opts):
2011 2011 """pop the current patch off the stack
2012 2012
2013 2013 By default, pops off the top of the patch stack. If given a patch name,
2014 2014 keeps popping off patches until the named patch is at the top of the stack.
2015 2015 """
2016 2016 localupdate = True
2017 2017 if opts['name']:
2018 2018 q = queue(ui, repo.join(""), repo.join(opts['name']))
2019 2019 ui.warn(_('using patch queue: %s\n') % q.path)
2020 2020 localupdate = False
2021 2021 else:
2022 2022 q = repo.mq
2023 2023 ret = q.pop(repo, patch, force=opts['force'], update=localupdate,
2024 2024 all=opts['all'])
2025 2025 q.save_dirty()
2026 2026 return ret
2027 2027
2028 2028 def rename(ui, repo, patch, name=None, **opts):
2029 2029 """rename a patch
2030 2030
2031 2031 With one argument, renames the current patch to PATCH1.
2032 2032 With two arguments, renames PATCH1 to PATCH2."""
2033 2033
2034 2034 q = repo.mq
2035 2035
2036 2036 if not name:
2037 2037 name = patch
2038 2038 patch = None
2039 2039
2040 2040 if patch:
2041 2041 patch = q.lookup(patch)
2042 2042 else:
2043 2043 if not q.applied:
2044 2044 ui.write(_('No patches applied\n'))
2045 2045 return
2046 2046 patch = q.lookup('qtip')
2047 2047 absdest = q.join(name)
2048 2048 if os.path.isdir(absdest):
2049 2049 name = normname(os.path.join(name, os.path.basename(patch)))
2050 2050 absdest = q.join(name)
2051 2051 if os.path.exists(absdest):
2052 2052 raise util.Abort(_('%s already exists') % absdest)
2053 2053
2054 2054 if name in q.series:
2055 2055 raise util.Abort(_('A patch named %s already exists in the series file') % name)
2056 2056
2057 2057 if ui.verbose:
2058 2058 ui.write('Renaming %s to %s\n' % (patch, name))
2059 2059 i = q.find_series(patch)
2060 2060 guards = q.guard_re.findall(q.full_series[i])
2061 2061 q.full_series[i] = name + ''.join([' #' + g for g in guards])
2062 2062 q.parse_series()
2063 2063 q.series_dirty = 1
2064 2064
2065 2065 info = q.isapplied(patch)
2066 2066 if info:
2067 2067 q.applied[info[0]] = statusentry(info[1], name)
2068 2068 q.applied_dirty = 1
2069 2069
2070 2070 util.rename(q.join(patch), absdest)
2071 2071 r = q.qrepo()
2072 2072 if r:
2073 2073 wlock = r.wlock()
2074 2074 try:
2075 2075 if r.dirstate[patch] == 'a':
2076 2076 r.dirstate.forget(patch)
2077 2077 r.dirstate.add(name)
2078 2078 else:
2079 2079 if r.dirstate[name] == 'r':
2080 2080 r.undelete([name])
2081 2081 r.copy(patch, name)
2082 2082 r.remove([patch], False)
2083 2083 finally:
2084 2084 del wlock
2085 2085
2086 2086 q.save_dirty()
2087 2087
2088 2088 def restore(ui, repo, rev, **opts):
2089 2089 """restore the queue state saved by a rev"""
2090 2090 rev = repo.lookup(rev)
2091 2091 q = repo.mq
2092 2092 q.restore(repo, rev, delete=opts['delete'],
2093 2093 qupdate=opts['update'])
2094 2094 q.save_dirty()
2095 2095 return 0
2096 2096
2097 2097 def save(ui, repo, **opts):
2098 2098 """save current queue state"""
2099 2099 q = repo.mq
2100 2100 message = cmdutil.logmessage(opts)
2101 2101 ret = q.save(repo, msg=message)
2102 2102 if ret:
2103 2103 return ret
2104 2104 q.save_dirty()
2105 2105 if opts['copy']:
2106 2106 path = q.path
2107 2107 if opts['name']:
2108 2108 newpath = os.path.join(q.basepath, opts['name'])
2109 2109 if os.path.exists(newpath):
2110 2110 if not os.path.isdir(newpath):
2111 2111 raise util.Abort(_('destination %s exists and is not '
2112 2112 'a directory') % newpath)
2113 2113 if not opts['force']:
2114 2114 raise util.Abort(_('destination %s exists, '
2115 2115 'use -f to force') % newpath)
2116 2116 else:
2117 2117 newpath = savename(path)
2118 2118 ui.warn(_("copy %s to %s\n") % (path, newpath))
2119 2119 util.copyfiles(path, newpath)
2120 2120 if opts['empty']:
2121 2121 try:
2122 2122 os.unlink(q.join(q.status_path))
2123 2123 except:
2124 2124 pass
2125 2125 return 0
2126 2126
2127 2127 def strip(ui, repo, rev, **opts):
2128 2128 """strip a revision and all its descendants from the repository
2129 2129
2130 2130 If one of the working dir's parent revisions is stripped, the working
2131 2131 directory will be updated to the parent of the stripped revision.
2132 2132 """
2133 2133 backup = 'all'
2134 2134 if opts['backup']:
2135 2135 backup = 'strip'
2136 2136 elif opts['nobackup']:
2137 2137 backup = 'none'
2138 2138
2139 2139 rev = repo.lookup(rev)
2140 2140 p = repo.dirstate.parents()
2141 2141 cl = repo.changelog
2142 2142 update = True
2143 2143 if p[0] == revlog.nullid:
2144 2144 update = False
2145 2145 elif p[1] == revlog.nullid and rev != cl.ancestor(p[0], rev):
2146 2146 update = False
2147 2147 elif rev not in (cl.ancestor(p[0], rev), cl.ancestor(p[1], rev)):
2148 2148 update = False
2149 2149
2150 2150 repo.mq.strip(repo, rev, backup=backup, update=update, force=opts['force'])
2151 2151 return 0
2152 2152
2153 2153 def select(ui, repo, *args, **opts):
2154 2154 '''set or print guarded patches to push
2155 2155
2156 2156 Use the qguard command to set or print guards on patch, then use
2157 2157 qselect to tell mq which guards to use. A patch will be pushed if it
2158 2158 has no guards or any positive guards match the currently selected guard,
2159 2159 but will not be pushed if any negative guards match the current guard.
2160 2160 For example:
2161 2161
2162 2162 qguard foo.patch -stable (negative guard)
2163 2163 qguard bar.patch +stable (positive guard)
2164 2164 qselect stable
2165 2165
2166 2166 This activates the "stable" guard. mq will skip foo.patch (because
2167 2167 it has a negative match) but push bar.patch (because it
2168 2168 has a positive match).
2169 2169
2170 2170 With no arguments, prints the currently active guards.
2171 2171 With one argument, sets the active guard.
2172 2172
2173 2173 Use -n/--none to deactivate guards (no other arguments needed).
2174 2174 When no guards are active, patches with positive guards are skipped
2175 2175 and patches with negative guards are pushed.
2176 2176
2177 2177 qselect can change the guards on applied patches. It does not pop
2178 2178 guarded patches by default. Use --pop to pop back to the last applied
2179 2179 patch that is not guarded. Use --reapply (which implies --pop) to push
2180 2180 back to the current patch afterwards, but skip guarded patches.
2181 2181
2182 2182 Use -s/--series to print a list of all guards in the series file (no
2183 2183 other arguments needed). Use -v for more information.'''
2184 2184
2185 2185 q = repo.mq
2186 2186 guards = q.active()
2187 2187 if args or opts['none']:
2188 2188 old_unapplied = q.unapplied(repo)
2189 2189 old_guarded = [i for i in xrange(len(q.applied)) if
2190 2190 not q.pushable(i)[0]]
2191 2191 q.set_active(args)
2192 2192 q.save_dirty()
2193 2193 if not args:
2194 2194 ui.status(_('guards deactivated\n'))
2195 2195 if not opts['pop'] and not opts['reapply']:
2196 2196 unapplied = q.unapplied(repo)
2197 2197 guarded = [i for i in xrange(len(q.applied))
2198 2198 if not q.pushable(i)[0]]
2199 2199 if len(unapplied) != len(old_unapplied):
2200 2200 ui.status(_('number of unguarded, unapplied patches has '
2201 2201 'changed from %d to %d\n') %
2202 2202 (len(old_unapplied), len(unapplied)))
2203 2203 if len(guarded) != len(old_guarded):
2204 2204 ui.status(_('number of guarded, applied patches has changed '
2205 2205 'from %d to %d\n') %
2206 2206 (len(old_guarded), len(guarded)))
2207 2207 elif opts['series']:
2208 2208 guards = {}
2209 2209 noguards = 0
2210 2210 for gs in q.series_guards:
2211 2211 if not gs:
2212 2212 noguards += 1
2213 2213 for g in gs:
2214 2214 guards.setdefault(g, 0)
2215 2215 guards[g] += 1
2216 2216 if ui.verbose:
2217 2217 guards['NONE'] = noguards
2218 2218 guards = guards.items()
2219 2219 guards.sort(lambda a, b: cmp(a[0][1:], b[0][1:]))
2220 2220 if guards:
2221 2221 ui.note(_('guards in series file:\n'))
2222 2222 for guard, count in guards:
2223 2223 ui.note('%2d ' % count)
2224 2224 ui.write(guard, '\n')
2225 2225 else:
2226 2226 ui.note(_('no guards in series file\n'))
2227 2227 else:
2228 2228 if guards:
2229 2229 ui.note(_('active guards:\n'))
2230 2230 for g in guards:
2231 2231 ui.write(g, '\n')
2232 2232 else:
2233 2233 ui.write(_('no active guards\n'))
2234 2234 reapply = opts['reapply'] and q.applied and q.appliedname(-1)
2235 2235 popped = False
2236 2236 if opts['pop'] or opts['reapply']:
2237 2237 for i in xrange(len(q.applied)):
2238 2238 pushable, reason = q.pushable(i)
2239 2239 if not pushable:
2240 2240 ui.status(_('popping guarded patches\n'))
2241 2241 popped = True
2242 2242 if i == 0:
2243 2243 q.pop(repo, all=True)
2244 2244 else:
2245 2245 q.pop(repo, i-1)
2246 2246 break
2247 2247 if popped:
2248 2248 try:
2249 2249 if reapply:
2250 2250 ui.status(_('reapplying unguarded patches\n'))
2251 2251 q.push(repo, reapply)
2252 2252 finally:
2253 2253 q.save_dirty()
2254 2254
2255 2255 def finish(ui, repo, *revrange, **opts):
2256 2256 """move applied patches into repository history
2257 2257
2258 2258 Finishes the specified revisions (corresponding to applied patches) by
2259 2259 moving them out of mq control into regular repository history.
2260 2260
2261 2261 Accepts a revision range or the --applied option. If --applied is
2262 2262 specified, all applied mq revisions are removed from mq control.
2263 2263 Otherwise, the given revisions must be at the base of the stack of
2264 2264 applied patches.
2265 2265
2266 2266 This can be especially useful if your changes have been applied to an
2267 2267 upstream repository, or if you are about to push your changes to upstream.
2268 2268 """
2269 2269 if not opts['applied'] and not revrange:
2270 2270 raise util.Abort(_('no revisions specified'))
2271 2271 elif opts['applied']:
2272 2272 revrange = ('qbase:qtip',) + revrange
2273 2273
2274 2274 q = repo.mq
2275 2275 if not q.applied:
2276 2276 ui.status(_('no patches applied\n'))
2277 2277 return 0
2278 2278
2279 2279 revs = cmdutil.revrange(repo, revrange)
2280 2280 q.finish(repo, revs)
2281 2281 q.save_dirty()
2282 2282 return 0
2283 2283
2284 2284 def reposetup(ui, repo):
2285 2285 class mqrepo(repo.__class__):
2286 2286 def abort_if_wdir_patched(self, errmsg, force=False):
2287 2287 if self.mq.applied and not force:
2288 2288 parent = revlog.hex(self.dirstate.parents()[0])
2289 2289 if parent in [s.rev for s in self.mq.applied]:
2290 2290 raise util.Abort(errmsg)
2291 2291
2292 2292 def commit(self, *args, **opts):
2293 2293 if len(args) >= 6:
2294 2294 force = args[5]
2295 2295 else:
2296 2296 force = opts.get('force')
2297 2297 self.abort_if_wdir_patched(
2298 2298 _('cannot commit over an applied mq patch'),
2299 2299 force)
2300 2300
2301 2301 return super(mqrepo, self).commit(*args, **opts)
2302 2302
2303 2303 def push(self, remote, force=False, revs=None):
2304 2304 if self.mq.applied and not force and not revs:
2305 2305 raise util.Abort(_('source has mq patches applied'))
2306 2306 return super(mqrepo, self).push(remote, force, revs)
2307 2307
2308 2308 def tags(self):
2309 2309 if self.tagscache:
2310 2310 return self.tagscache
2311 2311
2312 2312 tagscache = super(mqrepo, self).tags()
2313 2313
2314 2314 q = self.mq
2315 2315 if not q.applied:
2316 2316 return tagscache
2317 2317
2318 2318 mqtags = [(revlog.bin(patch.rev), patch.name) for patch in q.applied]
2319 2319
2320 2320 if mqtags[-1][0] not in self.changelog.nodemap:
2321 2321 self.ui.warn(_('mq status file refers to unknown node %s\n')
2322 2322 % revlog.short(mqtags[-1][0]))
2323 2323 return tagscache
2324 2324
2325 2325 mqtags.append((mqtags[-1][0], 'qtip'))
2326 2326 mqtags.append((mqtags[0][0], 'qbase'))
2327 2327 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
2328 2328 for patch in mqtags:
2329 2329 if patch[1] in tagscache:
2330 2330 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
2331 2331 % patch[1])
2332 2332 else:
2333 2333 tagscache[patch[1]] = patch[0]
2334 2334
2335 2335 return tagscache
2336 2336
2337 2337 def _branchtags(self, partial, lrev):
2338 2338 q = self.mq
2339 2339 if not q.applied:
2340 2340 return super(mqrepo, self)._branchtags(partial, lrev)
2341 2341
2342 2342 cl = self.changelog
2343 2343 qbasenode = revlog.bin(q.applied[0].rev)
2344 2344 if qbasenode not in cl.nodemap:
2345 2345 self.ui.warn(_('mq status file refers to unknown node %s\n')
2346 2346 % revlog.short(qbasenode))
2347 2347 return super(mqrepo, self)._branchtags(partial, lrev)
2348 2348
2349 2349 qbase = cl.rev(qbasenode)
2350 2350 start = lrev + 1
2351 2351 if start < qbase:
2352 2352 # update the cache (excluding the patches) and save it
2353 2353 self._updatebranchcache(partial, lrev+1, qbase)
2354 2354 self._writebranchcache(partial, cl.node(qbase-1), qbase-1)
2355 2355 start = qbase
2356 2356 # if start = qbase, the cache is as updated as it should be.
2357 2357 # if start > qbase, the cache includes (part of) the patches.
2358 2358 # we might as well use it, but we won't save it.
2359 2359
2360 2360 # update the cache up to the tip
2361 2361 self._updatebranchcache(partial, start, len(cl))
2362 2362
2363 2363 return partial
2364 2364
2365 2365 if repo.local():
2366 2366 repo.__class__ = mqrepo
2367 2367 repo.mq = queue(ui, repo.join(""))
2368 2368
2369 def mqimport(orig, ui, repo, *args, **kwargs):
2370 if hasattr(repo, 'abort_if_wdir_patched'):
2371 repo.abort_if_wdir_patched(_('cannot import over an applied patch'),
2372 kwargs.get('force'))
2373 return orig(ui, repo, *args, **kwargs)
2374
2369 2375 def uisetup(ui):
2370 # override import to disallow importing over patch
2371 importalias, importcmd = cmdutil.findcmd('import', commands.table)
2372 for alias, cmd in commands.table.iteritems():
2373 if cmd is importcmd:
2374 importkey = alias
2375 break
2376 orig_import = importcmd[0]
2377 def mqimport(ui, repo, patch1, *patches, **opts):
2378 if hasattr(repo, 'abort_if_wdir_patched'):
2379 repo.abort_if_wdir_patched(_('cannot import over an applied patch'),
2380 opts.get('force'))
2381 orig_import(ui, repo, patch1, *patches, **opts)
2382 importcmd = list(importcmd)
2383 importcmd[0] = mqimport
2384 commands.table[importkey] = tuple(importcmd)
2376 extensions.wrapcommand(commands.table, 'import', mqimport)
2385 2377
2386 2378 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
2387 2379
2388 2380 cmdtable = {
2389 2381 "qapplied": (applied, [] + seriesopts, _('hg qapplied [-s] [PATCH]')),
2390 2382 "qclone":
2391 2383 (clone,
2392 2384 [('', 'pull', None, _('use pull protocol to copy metadata')),
2393 2385 ('U', 'noupdate', None, _('do not update the new working directories')),
2394 2386 ('', 'uncompressed', None,
2395 2387 _('use uncompressed transfer (fast over LAN)')),
2396 2388 ('p', 'patches', '', _('location of source patch repo')),
2397 2389 ] + commands.remoteopts,
2398 2390 _('hg qclone [OPTION]... SOURCE [DEST]')),
2399 2391 "qcommit|qci":
2400 2392 (commit,
2401 2393 commands.table["^commit|ci"][1],
2402 2394 _('hg qcommit [OPTION]... [FILE]...')),
2403 2395 "^qdiff":
2404 2396 (diff,
2405 2397 commands.diffopts + commands.diffopts2 + commands.walkopts,
2406 2398 _('hg qdiff [OPTION]... [FILE]...')),
2407 2399 "qdelete|qremove|qrm":
2408 2400 (delete,
2409 2401 [('k', 'keep', None, _('keep patch file')),
2410 2402 ('r', 'rev', [], _('stop managing a revision'))],
2411 2403 _('hg qdelete [-k] [-r REV]... [PATCH]...')),
2412 2404 'qfold':
2413 2405 (fold,
2414 2406 [('e', 'edit', None, _('edit patch header')),
2415 2407 ('k', 'keep', None, _('keep folded patch files')),
2416 2408 ] + commands.commitopts,
2417 2409 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...')),
2418 2410 'qgoto':
2419 2411 (goto,
2420 2412 [('f', 'force', None, _('overwrite any local changes'))],
2421 2413 _('hg qgoto [OPTION]... PATCH')),
2422 2414 'qguard':
2423 2415 (guard,
2424 2416 [('l', 'list', None, _('list all patches and guards')),
2425 2417 ('n', 'none', None, _('drop all guards'))],
2426 2418 _('hg qguard [-l] [-n] [PATCH] [+GUARD]... [-GUARD]...')),
2427 2419 'qheader': (header, [], _('hg qheader [PATCH]')),
2428 2420 "^qimport":
2429 2421 (qimport,
2430 2422 [('e', 'existing', None, _('import file in patch dir')),
2431 2423 ('n', 'name', '', _('patch file name')),
2432 2424 ('f', 'force', None, _('overwrite existing files')),
2433 2425 ('r', 'rev', [], _('place existing revisions under mq control')),
2434 2426 ('g', 'git', None, _('use git extended diff format'))],
2435 2427 _('hg qimport [-e] [-n NAME] [-f] [-g] [-r REV]... FILE...')),
2436 2428 "^qinit":
2437 2429 (init,
2438 2430 [('c', 'create-repo', None, _('create queue repository'))],
2439 2431 _('hg qinit [-c]')),
2440 2432 "qnew":
2441 2433 (new,
2442 2434 [('e', 'edit', None, _('edit commit message')),
2443 2435 ('f', 'force', None, _('import uncommitted changes into patch')),
2444 2436 ('g', 'git', None, _('use git extended diff format')),
2445 2437 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2446 2438 ('u', 'user', '', _('add "From: <given user>" to patch')),
2447 2439 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2448 2440 ('d', 'date', '', _('add "Date: <given date>" to patch'))
2449 2441 ] + commands.walkopts + commands.commitopts,
2450 2442 _('hg qnew [-e] [-m TEXT] [-l FILE] [-f] PATCH [FILE]...')),
2451 2443 "qnext": (next, [] + seriesopts, _('hg qnext [-s]')),
2452 2444 "qprev": (prev, [] + seriesopts, _('hg qprev [-s]')),
2453 2445 "^qpop":
2454 2446 (pop,
2455 2447 [('a', 'all', None, _('pop all patches')),
2456 2448 ('n', 'name', '', _('queue name to pop')),
2457 2449 ('f', 'force', None, _('forget any local changes'))],
2458 2450 _('hg qpop [-a] [-n NAME] [-f] [PATCH | INDEX]')),
2459 2451 "^qpush":
2460 2452 (push,
2461 2453 [('f', 'force', None, _('apply if the patch has rejects')),
2462 2454 ('l', 'list', None, _('list patch name in commit text')),
2463 2455 ('a', 'all', None, _('apply all patches')),
2464 2456 ('m', 'merge', None, _('merge from another queue')),
2465 2457 ('n', 'name', '', _('merge queue name'))],
2466 2458 _('hg qpush [-f] [-l] [-a] [-m] [-n NAME] [PATCH | INDEX]')),
2467 2459 "^qrefresh":
2468 2460 (refresh,
2469 2461 [('e', 'edit', None, _('edit commit message')),
2470 2462 ('g', 'git', None, _('use git extended diff format')),
2471 2463 ('s', 'short', None, _('refresh only files already in the patch and specified files')),
2472 2464 ('U', 'currentuser', None, _('add/update "From: <current user>" in patch')),
2473 2465 ('u', 'user', '', _('add/update "From: <given user>" in patch')),
2474 2466 ('D', 'currentdate', None, _('update "Date: <current date>" in patch (if present)')),
2475 2467 ('d', 'date', '', _('update "Date: <given date>" in patch (if present)'))
2476 2468 ] + commands.walkopts + commands.commitopts,
2477 2469 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...')),
2478 2470 'qrename|qmv':
2479 2471 (rename, [], _('hg qrename PATCH1 [PATCH2]')),
2480 2472 "qrestore":
2481 2473 (restore,
2482 2474 [('d', 'delete', None, _('delete save entry')),
2483 2475 ('u', 'update', None, _('update queue working dir'))],
2484 2476 _('hg qrestore [-d] [-u] REV')),
2485 2477 "qsave":
2486 2478 (save,
2487 2479 [('c', 'copy', None, _('copy patch directory')),
2488 2480 ('n', 'name', '', _('copy directory name')),
2489 2481 ('e', 'empty', None, _('clear queue status file')),
2490 2482 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2491 2483 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]')),
2492 2484 "qselect":
2493 2485 (select,
2494 2486 [('n', 'none', None, _('disable all guards')),
2495 2487 ('s', 'series', None, _('list all guards in series file')),
2496 2488 ('', 'pop', None, _('pop to before first guarded applied patch')),
2497 2489 ('', 'reapply', None, _('pop, then reapply patches'))],
2498 2490 _('hg qselect [OPTION]... [GUARD]...')),
2499 2491 "qseries":
2500 2492 (series,
2501 2493 [('m', 'missing', None, _('print patches not in series')),
2502 2494 ] + seriesopts,
2503 2495 _('hg qseries [-ms]')),
2504 2496 "^strip":
2505 2497 (strip,
2506 2498 [('f', 'force', None, _('force removal with local changes')),
2507 2499 ('b', 'backup', None, _('bundle unrelated changesets')),
2508 2500 ('n', 'nobackup', None, _('no backups'))],
2509 2501 _('hg strip [-f] [-b] [-n] REV')),
2510 2502 "qtop": (top, [] + seriesopts, _('hg qtop [-s]')),
2511 2503 "qunapplied": (unapplied, [] + seriesopts, _('hg qunapplied [-s] [PATCH]')),
2512 2504 "qfinish":
2513 2505 (finish,
2514 2506 [('a', 'applied', None, _('finish all applied changesets'))],
2515 2507 _('hg qfinish [-a] [REV...]')),
2516 2508 }
@@ -1,65 +1,64 b''
1 1 # pager.py - display output using a pager
2 2 #
3 3 # Copyright 2008 David Soria Parra <dsp@php.net>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7 #
8 8 # To load the extension, add it to your .hgrc file:
9 9 #
10 10 # [extension]
11 11 # hgext.pager =
12 12 #
13 13 # Run "hg help pager" to get info on configuration.
14 14
15 15 '''browse command output with external pager
16 16
17 17 To set the pager that should be used, set the application variable:
18 18
19 19 [pager]
20 20 pager = LESS='FSRX' less
21 21
22 22 If no pager is set, the pager extensions uses the environment
23 23 variable $PAGER. If neither pager.pager, nor $PAGER is set, no pager
24 24 is used.
25 25
26 26 If you notice "BROKEN PIPE" error messages, you can disable them
27 27 by setting:
28 28
29 29 [pager]
30 30 quiet = True
31 31
32 32 You can disable the pager for certain commands by adding them to the
33 33 pager.ignore list:
34 34
35 35 [pager]
36 36 ignore = version, help, update
37 37
38 38 You can also enable the pager only for certain commands using pager.attend:
39 39
40 40 [pager]
41 41 attend = log
42 42
43 43 If pager.attend is present, pager.ignore will be ignored.
44 44
45 45 To ignore global commands like "hg version" or "hg help", you have to specify
46 46 them in the global .hgrc
47 47 '''
48 48
49 49 import sys, os, signal
50 from mercurial import dispatch, util
50 from mercurial import dispatch, util, extensions
51 51
52 52 def uisetup(ui):
53 def pagecmd(ui, options, cmd, cmdfunc):
53 def pagecmd(orig, ui, options, cmd, cmdfunc):
54 54 p = ui.config("pager", "pager", os.environ.get("PAGER"))
55 55 if p and sys.stdout.isatty() and '--debugger' not in sys.argv:
56 56 attend = ui.configlist('pager', 'attend')
57 57 if (cmd in attend or
58 58 (cmd not in ui.configlist('pager', 'ignore') and not attend)):
59 59 sys.stderr = sys.stdout = util.popen(p, "wb")
60 60 if ui.configbool('pager', 'quiet'):
61 61 signal.signal(signal.SIGPIPE, signal.SIG_DFL)
62 return oldrun(ui, options, cmd, cmdfunc)
62 return orig(ui, options, cmd, cmdfunc)
63 63
64 oldrun = dispatch._runcommand
65 dispatch._runcommand = pagecmd
64 extensions.wrapfunction(dispatch, '_runcommand', pagecmd)
@@ -1,403 +1,391 b''
1 1 # rebase.py - rebasing feature for mercurial
2 2 #
3 3 # Copyright 2008 Stefano Tortarolo <stefano.tortarolo at gmail dot com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7
8 8 '''move sets of revisions to a different ancestor
9 9
10 10 This extension lets you rebase changesets in an existing Mercurial repository.
11 11
12 12 For more information:
13 13 http://www.selenic.com/mercurial/wiki/index.cgi/RebaseProject
14 14 '''
15 15
16 from mercurial import util, repair, merge, cmdutil, dispatch, commands
16 from mercurial import util, repair, merge, cmdutil, dispatch, commands, extensions
17 17 from mercurial.commands import templateopts
18 18 from mercurial.node import nullrev
19 19 from mercurial.i18n import _
20 20 import os, errno
21 21
22 22 def rebase(ui, repo, **opts):
23 23 """move changeset (and descendants) to a different branch
24 24
25 25 Rebase uses repeated merging to graft changesets from one part of history
26 26 onto another. This can be useful for linearizing local changes relative to
27 27 a master development tree.
28 28
29 29 If a rebase is interrupted to manually resolve a merge, it can be continued
30 30 with --continue or aborted with --abort.
31 31 """
32 32 originalwd = target = source = None
33 33 external = nullrev
34 34 state = skipped = {}
35 35
36 36 lock = wlock = None
37 37 try:
38 38 lock = repo.lock()
39 39 wlock = repo.wlock()
40 40
41 41 # Validate input and define rebasing points
42 42 destf = opts.get('dest', None)
43 43 srcf = opts.get('source', None)
44 44 basef = opts.get('base', None)
45 45 contf = opts.get('continue')
46 46 abortf = opts.get('abort')
47 47 collapsef = opts.get('collapse', False)
48 48 if contf or abortf:
49 49 if contf and abortf:
50 50 raise dispatch.ParseError('rebase',
51 51 _('cannot use both abort and continue'))
52 52 if collapsef:
53 53 raise dispatch.ParseError('rebase',
54 54 _('cannot use collapse with continue or abort'))
55 55
56 56 if (srcf or basef or destf):
57 57 raise dispatch.ParseError('rebase',
58 58 _('abort and continue do not allow specifying revisions'))
59 59
60 60 originalwd, target, state, collapsef, external = restorestatus(repo)
61 61 if abortf:
62 62 abort(repo, originalwd, target, state)
63 63 return
64 64 else:
65 65 if srcf and basef:
66 66 raise dispatch.ParseError('rebase', _('cannot specify both a '
67 67 'revision and a base'))
68 68 cmdutil.bail_if_changed(repo)
69 69 result = buildstate(repo, destf, srcf, basef, collapsef)
70 70 if result:
71 71 originalwd, target, state, external = result
72 72 else: # Empty state built, nothing to rebase
73 73 repo.ui.status(_('nothing to rebase\n'))
74 74 return
75 75
76 76 # Rebase
77 77 targetancestors = list(repo.changelog.ancestors(target))
78 78 targetancestors.append(target)
79 79
80 80 for rev in util.sort(state):
81 81 if state[rev] == -1:
82 82 storestatus(repo, originalwd, target, state, collapsef,
83 83 external)
84 84 rebasenode(repo, rev, target, state, skipped, targetancestors,
85 85 collapsef)
86 86 ui.note(_('rebase merging completed\n'))
87 87
88 88 if collapsef:
89 89 p1, p2 = defineparents(repo, min(state), target,
90 90 state, targetancestors)
91 91 concludenode(repo, rev, p1, external, state, collapsef,
92 92 last=True, skipped=skipped)
93 93
94 94 if 'qtip' in repo.tags():
95 95 updatemq(repo, state, skipped, **opts)
96 96
97 97 if not opts.get('keep'):
98 98 # Remove no more useful revisions
99 99 if (util.set(repo.changelog.descendants(min(state)))
100 100 - util.set(state.keys())):
101 101 ui.warn(_("warning: new changesets detected on source branch, "
102 102 "not stripping\n"))
103 103 else:
104 104 repair.strip(repo.ui, repo, repo[min(state)].node(), "strip")
105 105
106 106 clearstatus(repo)
107 107 ui.status(_("rebase completed\n"))
108 108 if os.path.exists(repo.sjoin('undo')):
109 109 util.unlink(repo.sjoin('undo'))
110 110 if skipped:
111 111 ui.note(_("%d revisions have been skipped\n") % len(skipped))
112 112 finally:
113 113 del lock, wlock
114 114
115 115 def concludenode(repo, rev, p1, p2, state, collapse, last=False, skipped={}):
116 116 """Skip commit if collapsing has been required and rev is not the last
117 117 revision, commit otherwise
118 118 """
119 119 repo.dirstate.setparents(repo[p1].node(), repo[p2].node())
120 120
121 121 if collapse and not last:
122 122 return None
123 123
124 124 # Commit, record the old nodeid
125 125 m, a, r = repo.status()[:3]
126 126 newrev = nullrev
127 127 try:
128 128 if last:
129 129 commitmsg = 'Collapsed revision'
130 130 for rebased in state:
131 131 if rebased not in skipped:
132 132 commitmsg += '\n* %s' % repo[rebased].description()
133 133 commitmsg = repo.ui.edit(commitmsg, repo.ui.username())
134 134 else:
135 135 commitmsg = repo[rev].description()
136 136 # Commit might fail if unresolved files exist
137 137 newrev = repo.commit(m+a+r,
138 138 text=commitmsg,
139 139 user=repo[rev].user(),
140 140 date=repo[rev].date(),
141 141 extra={'rebase_source': repo[rev].hex()})
142 142 return newrev
143 143 except util.Abort:
144 144 # Invalidate the previous setparents
145 145 repo.dirstate.invalidate()
146 146 raise
147 147
148 148 def rebasenode(repo, rev, target, state, skipped, targetancestors, collapse):
149 149 'Rebase a single revision'
150 150 repo.ui.debug(_("rebasing %d:%s\n") % (rev, repo[rev].node()))
151 151
152 152 p1, p2 = defineparents(repo, rev, target, state, targetancestors)
153 153
154 154 # Merge phase
155 155 if len(repo.parents()) != 2:
156 156 # Update to target and merge it with local
157 157 merge.update(repo, p1, False, True, False)
158 158 repo.dirstate.write()
159 159 stats = merge.update(repo, rev, True, False, False)
160 160
161 161 if stats[3] > 0:
162 162 raise util.Abort(_('fix unresolved conflicts with hg resolve then '
163 163 'run hg rebase --continue'))
164 164 else: # we have an interrupted rebase
165 165 repo.ui.debug(_('resuming interrupted rebase\n'))
166 166
167 167
168 168 newrev = concludenode(repo, rev, p1, p2, state, collapse)
169 169
170 170 # Update the state
171 171 if newrev is not None:
172 172 state[rev] = repo[newrev].rev()
173 173 else:
174 174 if not collapse:
175 175 repo.ui.note(_('no changes, revision %d skipped\n') % rev)
176 176 repo.ui.debug(_('next revision set to %s\n') % p1)
177 177 skipped[rev] = True
178 178 state[rev] = p1
179 179
180 180 def defineparents(repo, rev, target, state, targetancestors):
181 181 'Return the new parent relationship of the revision that will be rebased'
182 182 parents = repo[rev].parents()
183 183 p1 = p2 = nullrev
184 184
185 185 P1n = parents[0].rev()
186 186 if P1n in targetancestors:
187 187 p1 = target
188 188 elif P1n in state:
189 189 p1 = state[P1n]
190 190 else: # P1n external
191 191 p1 = target
192 192 p2 = P1n
193 193
194 194 if len(parents) == 2 and parents[1].rev() not in targetancestors:
195 195 P2n = parents[1].rev()
196 196 # interesting second parent
197 197 if P2n in state:
198 198 if p1 == target: # P1n in targetancestors or external
199 199 p1 = state[P2n]
200 200 else:
201 201 p2 = state[P2n]
202 202 else: # P2n external
203 203 if p2 != nullrev: # P1n external too => rev is a merged revision
204 204 raise util.Abort(_('cannot use revision %d as base, result '
205 205 'would have 3 parents') % rev)
206 206 p2 = P2n
207 207 return p1, p2
208 208
209 209 def updatemq(repo, state, skipped, **opts):
210 210 'Update rebased mq patches - finalize and then import them'
211 211 mqrebase = {}
212 212 for p in repo.mq.applied:
213 213 if repo[p.rev].rev() in state:
214 214 repo.ui.debug(_('revision %d is an mq patch (%s), finalize it.\n') %
215 215 (repo[p.rev].rev(), p.name))
216 216 mqrebase[repo[p.rev].rev()] = p.name
217 217
218 218 if mqrebase:
219 219 repo.mq.finish(repo, mqrebase.keys())
220 220
221 221 # We must start import from the newest revision
222 222 mq = mqrebase.keys()
223 223 mq.sort()
224 224 mq.reverse()
225 225 for rev in mq:
226 226 if rev not in skipped:
227 227 repo.ui.debug(_('import mq patch %d (%s)\n')
228 228 % (state[rev], mqrebase[rev]))
229 229 repo.mq.qimport(repo, (), patchname=mqrebase[rev],
230 230 git=opts.get('git', False),rev=[str(state[rev])])
231 231 repo.mq.save_dirty()
232 232
233 233 def storestatus(repo, originalwd, target, state, collapse, external):
234 234 'Store the current status to allow recovery'
235 235 f = repo.opener("rebasestate", "w")
236 236 f.write(repo[originalwd].hex() + '\n')
237 237 f.write(repo[target].hex() + '\n')
238 238 f.write(repo[external].hex() + '\n')
239 239 f.write('%d\n' % int(collapse))
240 240 for d, v in state.items():
241 241 oldrev = repo[d].hex()
242 242 newrev = repo[v].hex()
243 243 f.write("%s:%s\n" % (oldrev, newrev))
244 244 f.close()
245 245 repo.ui.debug(_('rebase status stored\n'))
246 246
247 247 def clearstatus(repo):
248 248 'Remove the status files'
249 249 if os.path.exists(repo.join("rebasestate")):
250 250 util.unlink(repo.join("rebasestate"))
251 251
252 252 def restorestatus(repo):
253 253 'Restore a previously stored status'
254 254 try:
255 255 target = None
256 256 collapse = False
257 257 external = nullrev
258 258 state = {}
259 259 f = repo.opener("rebasestate")
260 260 for i, l in enumerate(f.read().splitlines()):
261 261 if i == 0:
262 262 originalwd = repo[l].rev()
263 263 elif i == 1:
264 264 target = repo[l].rev()
265 265 elif i == 2:
266 266 external = repo[l].rev()
267 267 elif i == 3:
268 268 collapse = bool(int(l))
269 269 else:
270 270 oldrev, newrev = l.split(':')
271 271 state[repo[oldrev].rev()] = repo[newrev].rev()
272 272 repo.ui.debug(_('rebase status resumed\n'))
273 273 return originalwd, target, state, collapse, external
274 274 except IOError, err:
275 275 if err.errno != errno.ENOENT:
276 276 raise
277 277 raise util.Abort(_('no rebase in progress'))
278 278
279 279 def abort(repo, originalwd, target, state):
280 280 'Restore the repository to its original state'
281 281 if util.set(repo.changelog.descendants(target)) - util.set(state.values()):
282 282 repo.ui.warn(_("warning: new changesets detected on target branch, "
283 283 "not stripping\n"))
284 284 else:
285 285 # Strip from the first rebased revision
286 286 merge.update(repo, repo[originalwd].rev(), False, True, False)
287 287 rebased = filter(lambda x: x > -1, state.values())
288 288 if rebased:
289 289 strippoint = min(rebased)
290 290 repair.strip(repo.ui, repo, repo[strippoint].node(), "strip")
291 291 clearstatus(repo)
292 292 repo.ui.status(_('rebase aborted\n'))
293 293
294 294 def buildstate(repo, dest, src, base, collapse):
295 295 'Define which revisions are going to be rebased and where'
296 296 state = {}
297 297 targetancestors = util.set()
298 298
299 299 if not dest:
300 300 # Destination defaults to the latest revision in the current branch
301 301 branch = repo[None].branch()
302 302 dest = repo[branch].rev()
303 303 else:
304 304 if 'qtip' in repo.tags() and (repo[dest].hex() in
305 305 [s.rev for s in repo.mq.applied]):
306 306 raise util.Abort(_('cannot rebase onto an applied mq patch'))
307 307 dest = repo[dest].rev()
308 308
309 309 if src:
310 310 commonbase = repo[src].ancestor(repo[dest])
311 311 if commonbase == repo[src]:
312 312 raise util.Abort(_('cannot rebase an ancestor'))
313 313 if commonbase == repo[dest]:
314 314 raise util.Abort(_('cannot rebase a descendant'))
315 315 source = repo[src].rev()
316 316 else:
317 317 if base:
318 318 cwd = repo[base].rev()
319 319 else:
320 320 cwd = repo['.'].rev()
321 321
322 322 if cwd == dest:
323 323 repo.ui.debug(_('already working on current\n'))
324 324 return None
325 325
326 326 targetancestors = util.set(repo.changelog.ancestors(dest))
327 327 if cwd in targetancestors:
328 328 repo.ui.debug(_('already working on the current branch\n'))
329 329 return None
330 330
331 331 cwdancestors = util.set(repo.changelog.ancestors(cwd))
332 332 cwdancestors.add(cwd)
333 333 rebasingbranch = cwdancestors - targetancestors
334 334 source = min(rebasingbranch)
335 335
336 336 repo.ui.debug(_('rebase onto %d starting from %d\n') % (dest, source))
337 337 state = dict.fromkeys(repo.changelog.descendants(source), nullrev)
338 338 external = nullrev
339 339 if collapse:
340 340 if not targetancestors:
341 341 targetancestors = util.set(repo.changelog.ancestors(dest))
342 342 for rev in state:
343 343 # Check externals and fail if there are more than one
344 344 for p in repo[rev].parents():
345 345 if (p.rev() not in state and p.rev() != source
346 346 and p.rev() not in targetancestors):
347 347 if external != nullrev:
348 348 raise util.Abort(_('unable to collapse, there is more '
349 349 'than one external parent'))
350 350 external = p.rev()
351 351
352 352 state[source] = nullrev
353 353 return repo['.'].rev(), repo[dest].rev(), state, external
354 354
355 def pulldelegate(pullfunction, repo, *args, **opts):
355 def pullrebase(orig, ui, repo, *args, **opts):
356 356 'Call rebase after pull if the latter has been invoked with --rebase'
357 357 if opts.get('rebase'):
358 358 if opts.get('update'):
359 359 raise util.Abort(_('--update and --rebase are not compatible'))
360 360
361 361 cmdutil.bail_if_changed(repo)
362 362 revsprepull = len(repo)
363 pullfunction(repo.ui, repo, *args, **opts)
363 orig(ui, repo, *args, **opts)
364 364 revspostpull = len(repo)
365 365 if revspostpull > revsprepull:
366 rebase(repo.ui, repo, **opts)
366 rebase(ui, repo, **opts)
367 367 else:
368 pullfunction(repo.ui, repo, *args, **opts)
368 orig(ui, repo, *args, **opts)
369 369
370 370 def uisetup(ui):
371 371 'Replace pull with a decorator to provide --rebase option'
372 # cribbed from color.py
373 aliases, entry = cmdutil.findcmd('pull', commands.table)
374 for candidatekey, candidateentry in commands.table.iteritems():
375 if candidateentry is entry:
376 cmdkey, cmdentry = candidatekey, entry
377 break
378
379 decorator = lambda ui, repo, *args, **opts: \
380 pulldelegate(cmdentry[0], repo, *args, **opts)
381 # make sure 'hg help cmd' still works
382 decorator.__doc__ = cmdentry[0].__doc__
383 decoratorentry = (decorator,) + cmdentry[1:]
384 rebaseopt = ('', 'rebase', None,
385 _("rebase working directory to branch head"))
386 decoratorentry[1].append(rebaseopt)
387 commands.table[cmdkey] = decoratorentry
372 entry = extensions.wrapcommand(commands.table, 'pull', pullrebase)
373 entry[1].append(('', 'rebase', None,
374 _("rebase working directory to branch head"))
375 )
388 376
389 377 cmdtable = {
390 378 "rebase":
391 379 (rebase,
392 380 [
393 381 ('', 'keep', False, _('keep original revisions')),
394 382 ('s', 'source', '', _('rebase from a given revision')),
395 383 ('b', 'base', '', _('rebase from the base of a given revision')),
396 384 ('d', 'dest', '', _('rebase onto a given revision')),
397 385 ('', 'collapse', False, _('collapse the rebased revisions')),
398 386 ('c', 'continue', False, _('continue an interrupted rebase')),
399 387 ('a', 'abort', False, _('abort an interrupted rebase')),] +
400 388 templateopts,
401 389 _('hg rebase [-s rev | -b rev] [-d rev] [--collapse] | [-c] | [-a] | '
402 390 '[--keep]')),
403 391 }
@@ -1,135 +1,134 b''
1 1 # zeroconf.py - zeroconf support for Mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of
6 6 # the GNU General Public License (version 2), incorporated herein by
7 7 # reference.
8 8
9 9 import Zeroconf, socket, time, os
10 10 from mercurial import ui
11 from mercurial import extensions
11 12 from mercurial.hgweb import hgweb_mod
12 13 from mercurial.hgweb import hgwebdir_mod
13 14
14 15 # publish
15 16
16 17 server = None
17 18 localip = None
18 19
19 20 def getip():
20 21 # finds external-facing interface without sending any packets (Linux)
21 22 try:
22 23 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
23 24 s.connect(('1.0.0.1', 0))
24 25 ip = s.getsockname()[0]
25 26 return ip
26 27 except:
27 28 pass
28 29
29 30 # Generic method, sometimes gives useless results
30 31 dumbip = socket.gethostbyaddr(socket.gethostname())[2][0]
31 32 if not dumbip.startswith('127.'):
32 33 return dumbip
33 34
34 35 # works elsewhere, but actually sends a packet
35 36 try:
36 37 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
37 38 s.connect(('1.0.0.1', 1))
38 39 ip = s.getsockname()[0]
39 40 return ip
40 41 except:
41 42 pass
42 43
43 44 return dumbip
44 45
45 46 def publish(name, desc, path, port):
46 47 global server, localip
47 48 if not server:
48 49 server = Zeroconf.Zeroconf()
49 50 ip = getip()
50 51 localip = socket.inet_aton(ip)
51 52
52 53 parts = socket.gethostname().split('.')
53 54 host = parts[0] + ".local"
54 55
55 56 # advertise to browsers
56 57 svc = Zeroconf.ServiceInfo('_http._tcp.local.',
57 58 name + '._http._tcp.local.',
58 59 server = host,
59 60 port = port,
60 61 properties = {'description': desc,
61 62 'path': "/" + path},
62 63 address = localip, weight = 0, priority = 0)
63 64 server.registerService(svc)
64 65
65 66 # advertise to Mercurial clients
66 67 svc = Zeroconf.ServiceInfo('_hg._tcp.local.',
67 68 name + '._hg._tcp.local.',
68 69 server = host,
69 70 port = port,
70 71 properties = {'description': desc,
71 72 'path': "/" + path},
72 73 address = localip, weight = 0, priority = 0)
73 74 server.registerService(svc)
74 75
75 76 class hgwebzc(hgweb_mod.hgweb):
76 77 def __init__(self, repo, name=None):
77 78 super(hgwebzc, self).__init__(repo, name)
78 79 name = self.reponame or os.path.basename(repo.root)
79 80 desc = self.repo.ui.config("web", "description", name)
80 81 publish(name, desc, name, int(repo.ui.config("web", "port", 8000)))
81 82
82 83 class hgwebdirzc(hgwebdir_mod.hgwebdir):
83 84 def run(self):
84 85 print os.environ
85 86 for r, p in self.repos:
86 87 u = ui.ui(parentui=self.parentui)
87 88 u.readconfig(os.path.join(path, '.hg', 'hgrc'))
88 89 n = os.path.basename(r)
89 90 desc = u.config("web", "description", n)
90 91 publish(n, "hgweb", p, int(repo.ui.config("web", "port", 8000)))
91 92 return super(hgwebdirzc, self).run()
92 93
93 94 # listen
94 95
95 96 class listener(object):
96 97 def __init__(self):
97 98 self.found = {}
98 99 def removeService(self, server, type, name):
99 100 if repr(name) in self.found:
100 101 del self.found[repr(name)]
101 102 def addService(self, server, type, name):
102 103 self.found[repr(name)] = server.getServiceInfo(type, name)
103 104
104 105 def getzcpaths():
105 106 server = Zeroconf.Zeroconf()
106 107 l = listener()
107 108 browser = Zeroconf.ServiceBrowser(server, "_hg._tcp.local.", l)
108 109 time.sleep(1)
109 110 server.close()
110 111 for v in l.found.values():
111 112 n = v.name[:v.name.index('.')]
112 113 n.replace(" ", "-")
113 114 u = "http://%s:%s%s" % (socket.inet_ntoa(v.address), v.port,
114 115 v.properties.get("path", "/"))
115 116 yield "zc-" + n, u
116 117
117 def config(self, section, key, default=None, untrusted=False):
118 def config(orig, self, section, key, default=None, untrusted=False):
118 119 if section == "paths" and key.startswith("zc-"):
119 120 for n, p in getzcpaths():
120 121 if n == key:
121 122 return p
122 return oldconfig(self, section, key, default, untrusted)
123 return orig(self, section, key, default, untrusted)
123 124
124 def configitems(self, section):
125 r = oldconfigitems(self, section, untrusted=False)
125 def configitems(orig, self, section):
126 r = orig(self, section, untrusted=False)
126 127 if section == "paths":
127 128 r += getzcpaths()
128 129 return r
129 130
130 oldconfig = ui.ui.config
131 oldconfigitems = ui.ui.configitems
132 ui.ui.config = config
133 ui.ui.configitems = configitems
131 extensions.wrapfunction(ui.ui, 'config', config)
132 extensions.wrapfunction(ui.ui, 'configitems', configitems)
134 133 hgweb_mod.hgweb = hgwebzc
135 134 hgwebdir_mod.hgwebdir = hgwebdirzc
General Comments 0
You need to be logged in to leave comments. Login now