Add the 'sync' command
[stgit] / stgit / commands / common.py
1 """Function/variables common to all the commands
2 """
3
4 __copyright__ = """
5 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License version 2 as
9 published by the Free Software Foundation.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 """
20
21 import sys, os, os.path, re
22 from optparse import OptionParser, make_option
23
24 from stgit.utils import *
25 from stgit import stack, git, basedir
26 from stgit.config import config, file_extensions
27
28 crt_series = None
29
30
31 # Command exception class
32 class CmdException(Exception):
33 pass
34
35
36 # Utility functions
37 class RevParseException(Exception):
38 """Revision spec parse error."""
39 pass
40
41 def parse_rev(rev):
42 """Parse a revision specification into its
43 patchname@branchname//patch_id parts. If no branch name has a slash
44 in it, also accept / instead of //."""
45 files, dirs = list_files_and_dirs(os.path.join(basedir.get(),
46 'refs', 'heads'))
47 if len(dirs) != 0:
48 # We have branch names with / in them.
49 branch_chars = r'[^@]'
50 patch_id_mark = r'//'
51 else:
52 # No / in branch names.
53 branch_chars = r'[^@/]'
54 patch_id_mark = r'(/|//)'
55 patch_re = r'(?P<patch>[^@/]+)'
56 branch_re = r'@(?P<branch>%s+)' % branch_chars
57 patch_id_re = r'%s(?P<patch_id>[a-z.]*)' % patch_id_mark
58
59 # Try //patch_id.
60 m = re.match(r'^%s$' % patch_id_re, rev)
61 if m:
62 return None, None, m.group('patch_id')
63
64 # Try path[@branch]//patch_id.
65 m = re.match(r'^%s(%s)?%s$' % (patch_re, branch_re, patch_id_re), rev)
66 if m:
67 return m.group('patch'), m.group('branch'), m.group('patch_id')
68
69 # Try patch[@branch].
70 m = re.match(r'^%s(%s)?$' % (patch_re, branch_re), rev)
71 if m:
72 return m.group('patch'), m.group('branch'), None
73
74 # No, we can't parse that.
75 raise RevParseException
76
77 def git_id(rev):
78 """Return the GIT id
79 """
80 if not rev:
81 return None
82 try:
83 patch, branch, patch_id = parse_rev(rev)
84 if branch == None:
85 series = crt_series
86 else:
87 series = stack.Series(branch)
88 if patch == None:
89 patch = series.get_current()
90 if not patch:
91 raise CmdException, 'No patches applied'
92 if patch in series.get_applied() or patch in series.get_unapplied():
93 if patch_id in ['top', '', None]:
94 return series.get_patch(patch).get_top()
95 elif patch_id == 'bottom':
96 return series.get_patch(patch).get_bottom()
97 elif patch_id == 'top.old':
98 return series.get_patch(patch).get_old_top()
99 elif patch_id == 'bottom.old':
100 return series.get_patch(patch).get_old_bottom()
101 elif patch_id == 'log':
102 return series.get_patch(patch).get_log()
103 if patch == 'base' and patch_id == None:
104 return read_string(series.get_base_file())
105 except RevParseException:
106 pass
107 return git.rev_parse(rev + '^{commit}')
108
109 def check_local_changes():
110 if git.local_changes():
111 raise CmdException, \
112 'local changes in the tree. Use "refresh" or "status --reset"'
113
114 def check_head_top_equal():
115 if not crt_series.head_top_equal():
116 raise CmdException(
117 'HEAD and top are not the same. You probably committed\n'
118 ' changes to the tree outside of StGIT. To bring them\n'
119 ' into StGIT, use the "assimilate" command')
120
121 def check_conflicts():
122 if os.path.exists(os.path.join(basedir.get(), 'conflicts')):
123 raise CmdException, \
124 'Unsolved conflicts. Please resolve them first or\n' \
125 ' revert the changes with "status --reset"'
126
127 def print_crt_patch(branch = None):
128 if not branch:
129 patch = crt_series.get_current()
130 else:
131 patch = stack.Series(branch).get_current()
132
133 if patch:
134 print 'Now at patch "%s"' % patch
135 else:
136 print 'No patches applied'
137
138 def resolved(filename, reset = None):
139 if reset:
140 reset_file = filename + file_extensions()[reset]
141 if os.path.isfile(reset_file):
142 if os.path.isfile(filename):
143 os.remove(filename)
144 os.rename(reset_file, filename)
145
146 git.update_cache([filename], force = True)
147
148 for ext in file_extensions().values():
149 fn = filename + ext
150 if os.path.isfile(fn):
151 os.remove(fn)
152
153 def resolved_all(reset = None):
154 conflicts = git.get_conflicts()
155 if conflicts:
156 for filename in conflicts:
157 resolved(filename, reset)
158 os.remove(os.path.join(basedir.get(), 'conflicts'))
159
160 def push_patches(patches, check_merged = False):
161 """Push multiple patches onto the stack. This function is shared
162 between the push and pull commands
163 """
164 forwarded = crt_series.forward_patches(patches)
165 if forwarded > 1:
166 print 'Fast-forwarded patches "%s" - "%s"' % (patches[0],
167 patches[forwarded - 1])
168 elif forwarded == 1:
169 print 'Fast-forwarded patch "%s"' % patches[0]
170
171 names = patches[forwarded:]
172
173 # check for patches merged upstream
174 if check_merged:
175 print 'Checking for patches merged upstream...',
176 sys.stdout.flush()
177
178 merged = crt_series.merged_patches(names)
179
180 print 'done (%d found)' % len(merged)
181 else:
182 merged = []
183
184 for p in names:
185 print 'Pushing patch "%s"...' % p,
186 sys.stdout.flush()
187
188 if p in merged:
189 crt_series.push_patch(p, empty = True)
190 print 'done (merged upstream)'
191 else:
192 modified = crt_series.push_patch(p)
193
194 if crt_series.empty_patch(p):
195 print 'done (empty patch)'
196 elif modified:
197 print 'done (modified)'
198 else:
199 print 'done'
200
201 def pop_patches(patches, keep = False):
202 """Pop the patches in the list from the stack. It is assumed that
203 the patches are listed in the stack reverse order.
204 """
205 if len(patches) == 0:
206 print 'nothing to push/pop'
207 else:
208 p = patches[-1]
209 if len(patches) == 1:
210 print 'Popping patch "%s"...' % p,
211 else:
212 print 'Popping "%s" - "%s" patches...' % (patches[0], p),
213 sys.stdout.flush()
214
215 crt_series.pop_patch(p, keep)
216
217 print 'done'
218
219 def parse_patches(patch_args, patch_list, boundary = 0, ordered = False):
220 """Parse patch_args list for patch names in patch_list and return
221 a list. The names can be individual patches and/or in the
222 patch1..patch2 format.
223 """
224 patches = []
225
226 for name in patch_args:
227 pair = name.split('..')
228 for p in pair:
229 if p and not p in patch_list:
230 raise CmdException, 'Unknown patch name: %s' % p
231
232 if len(pair) == 1:
233 # single patch name
234 pl = pair
235 elif len(pair) == 2:
236 # patch range [p1]..[p2]
237 # inclusive boundary
238 if pair[0]:
239 first = patch_list.index(pair[0])
240 else:
241 first = -1
242 # exclusive boundary
243 if pair[1]:
244 last = patch_list.index(pair[1]) + 1
245 else:
246 last = -1
247
248 # only cross the boundary if explicitly asked
249 if not boundary:
250 boundary = len(patch_list)
251 if first < 0:
252 if last <= boundary:
253 first = 0
254 else:
255 first = boundary
256 if last < 0:
257 if first < boundary:
258 last = boundary
259 else:
260 last = len(patch_list)
261
262 if last > first:
263 pl = patch_list[first:last]
264 else:
265 pl = patch_list[(last - 1):(first + 1)]
266 pl.reverse()
267 else:
268 raise CmdException, 'Malformed patch name: %s' % name
269
270 for p in pl:
271 if p in patches:
272 raise CmdException, 'Duplicate patch name: %s' % p
273
274 patches += pl
275
276 if ordered:
277 patches = [p for p in patch_list if p in patches]
278
279 return patches
280
281 def name_email(address):
282 """Return a tuple consisting of the name and email parsed from a
283 standard 'name <email>' or 'email (name)' string
284 """
285 address = re.sub('[\\\\"]', '\\\\\g<0>', address)
286 str_list = re.findall('^(.*)\s*<(.*)>\s*$', address)
287 if not str_list:
288 str_list = re.findall('^(.*)\s*\((.*)\)\s*$', address)
289 if not str_list:
290 raise CmdException, 'Incorrect "name <email>"/"email (name)" string: %s' % address
291 return ( str_list[0][1], str_list[0][0] )
292
293 return str_list[0]
294
295 def name_email_date(address):
296 """Return a tuple consisting of the name, email and date parsed
297 from a 'name <email> date' string
298 """
299 address = re.sub('[\\\\"]', '\\\\\g<0>', address)
300 str_list = re.findall('^(.*)\s*<(.*)>\s*(.*)\s*$', address)
301 if not str_list:
302 raise CmdException, 'Incorrect "name <email> date" string: %s' % address
303
304 return str_list[0]
305
306 def patch_name_from_msg(msg):
307 """Return a string to be used as a patch name. This is generated
308 from the first 30 characters of the top line of the string passed
309 as argument."""
310 if not msg:
311 return None
312
313 subject_line = msg[:30].lstrip().split('\n', 1)[0].lower()
314 return re.sub('[\W]+', '-', subject_line).strip('-')
315
316 def make_patch_name(msg, unacceptable, default_name = 'patch',
317 alternative = True):
318 """Return a patch name generated from the given commit message,
319 guaranteed to make unacceptable(name) be false. If the commit
320 message is empty, base the name on default_name instead."""
321 patchname = patch_name_from_msg(msg)
322 if not patchname:
323 patchname = default_name
324 if alternative and unacceptable(patchname):
325 suffix = 0
326 while unacceptable('%s-%d' % (patchname, suffix)):
327 suffix += 1
328 patchname = '%s-%d' % (patchname, suffix)
329 return patchname