Remove the 'top' field
[stgit] / stgit / stack.py
CommitLineData
41a6d859
CM
1"""Basic quilt-like functionality
2"""
3
4__copyright__ = """
5Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
6
7This program is free software; you can redistribute it and/or modify
8it under the terms of the GNU General Public License version 2 as
9published by the Free Software Foundation.
10
11This program is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with this program; if not, write to the Free Software
18Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19"""
20
c1e4d7e0 21import sys, os, re
ed60fdae 22from email.Utils import formatdate
41a6d859 23
87c93eab 24from stgit.exception import *
41a6d859 25from stgit.utils import *
5e888f30 26from stgit.out import *
950b1095 27from stgit.run import *
1f3bb017 28from stgit import git, basedir, templates
41a6d859 29from stgit.config import config
8fce9909 30from shutil import copyfile
41a6d859
CM
31
32
33# stack exception class
87c93eab 34class StackException(StgException):
41a6d859
CM
35 pass
36
6ad48e48
PBG
37class FilterUntil:
38 def __init__(self):
39 self.should_print = True
40 def __call__(self, x, until_test, prefix):
41 if until_test(x):
42 self.should_print = False
43 if self.should_print:
44 return x[0:len(prefix)] != prefix
45 return False
46
41a6d859
CM
47#
48# Functions
49#
50__comment_prefix = 'STG:'
6ad48e48 51__patch_prefix = 'STG_PATCH:'
41a6d859
CM
52
53def __clean_comments(f):
54 """Removes lines marked for status in a commit file
55 """
56 f.seek(0)
57
58 # remove status-prefixed lines
6ad48e48
PBG
59 lines = f.readlines()
60
61 patch_filter = FilterUntil()
62 until_test = lambda t: t == (__patch_prefix + '\n')
63 lines = [l for l in lines if patch_filter(l, until_test, __comment_prefix)]
64
41a6d859
CM
65 # remove empty lines at the end
66 while len(lines) != 0 and lines[-1] == '\n':
67 del lines[-1]
68
69 f.seek(0); f.truncate()
70 f.writelines(lines)
71
ed60fdae
CM
72# TODO: move this out of the stgit.stack module, it is really for
73# higher level commands to handle the user interaction
7cc615f3 74def edit_file(series, line, comment, show_patch = True):
bd427e46 75 fname = '.stgitmsg.txt'
1f3bb017 76 tmpl = templates.get_template('patchdescr.tmpl')
41a6d859
CM
77
78 f = file(fname, 'w+')
7cc615f3
CL
79 if line:
80 print >> f, line
1f3bb017
CM
81 elif tmpl:
82 print >> f, tmpl,
41a6d859
CM
83 else:
84 print >> f
85 print >> f, __comment_prefix, comment
86 print >> f, __comment_prefix, \
87 'Lines prefixed with "%s" will be automatically removed.' \
88 % __comment_prefix
89 print >> f, __comment_prefix, \
90 'Trailing empty lines will be automatically removed.'
6ad48e48
PBG
91
92 if show_patch:
93 print >> f, __patch_prefix
94 # series.get_patch(series.get_current()).get_top()
f1c5519a
PR
95 diff_str = git.diff(rev1 = series.get_patch(series.get_current()).get_bottom())
96 f.write(diff_str)
6ad48e48
PBG
97
98 #Vim modeline must be near the end.
b83e37e0 99 print >> f, __comment_prefix, 'vi: set textwidth=75 filetype=diff nobackup:'
41a6d859
CM
100 f.close()
101
83bb4e4c 102 call_editor(fname)
41a6d859
CM
103
104 f = file(fname, 'r+')
105
106 __clean_comments(f)
107 f.seek(0)
7cc615f3 108 result = f.read()
41a6d859
CM
109
110 f.close()
111 os.remove(fname)
112
7cc615f3 113 return result
41a6d859
CM
114
115#
116# Classes
117#
118
8fe7e9f0
YD
119class StgitObject:
120 """An object with stgit-like properties stored as files in a directory
121 """
122 def _set_dir(self, dir):
123 self.__dir = dir
124 def _dir(self):
125 return self.__dir
126
127 def create_empty_field(self, name):
128 create_empty_file(os.path.join(self.__dir, name))
129
130 def _get_field(self, name, multiline = False):
131 id_file = os.path.join(self.__dir, name)
132 if os.path.isfile(id_file):
133 line = read_string(id_file, multiline)
134 if line == '':
135 return None
136 else:
137 return line
138 else:
139 return None
140
141 def _set_field(self, name, value, multiline = False):
142 fname = os.path.join(self.__dir, name)
143 if value and value != '':
144 write_string(fname, value, multiline)
145 elif os.path.isfile(fname):
146 os.remove(fname)
147
1981b663 148
8fe7e9f0 149class Patch(StgitObject):
41a6d859
CM
150 """Basic patch implementation
151 """
262d31dc
KH
152 def __init_refs(self):
153 self.__top_ref = self.__refs_base + '/' + self.__name
154 self.__log_ref = self.__top_ref + '.log'
155
156 def __init__(self, name, series_dir, refs_base):
02ac3ad2 157 self.__series_dir = series_dir
41a6d859 158 self.__name = name
8fe7e9f0 159 self._set_dir(os.path.join(self.__series_dir, self.__name))
262d31dc
KH
160 self.__refs_base = refs_base
161 self.__init_refs()
41a6d859
CM
162
163 def create(self):
8fe7e9f0 164 os.mkdir(self._dir())
41a6d859 165
c26ca1b2 166 def delete(self, keep_log = False):
42cd003e
CM
167 if os.path.isdir(self._dir()):
168 for f in os.listdir(self._dir()):
169 os.remove(os.path.join(self._dir(), f))
170 os.rmdir(self._dir())
171 else:
172 out.warn('Patch directory "%s" does not exist' % self._dir())
173 try:
174 # the reference might not exist if the repository was corrupted
175 git.delete_ref(self.__top_ref)
176 except git.GitException, e:
177 out.warn(str(e))
c26ca1b2 178 if not keep_log and git.ref_exists(self.__log_ref):
262d31dc 179 git.delete_ref(self.__log_ref)
41a6d859
CM
180
181 def get_name(self):
182 return self.__name
183
e55b53e0 184 def rename(self, newname):
8fe7e9f0 185 olddir = self._dir()
262d31dc
KH
186 old_top_ref = self.__top_ref
187 old_log_ref = self.__log_ref
e55b53e0 188 self.__name = newname
8fe7e9f0 189 self._set_dir(os.path.join(self.__series_dir, self.__name))
262d31dc 190 self.__init_refs()
e55b53e0 191
262d31dc
KH
192 git.rename_ref(old_top_ref, self.__top_ref)
193 if git.ref_exists(old_log_ref):
194 git.rename_ref(old_log_ref, self.__log_ref)
8fe7e9f0 195 os.rename(olddir, self._dir())
844a1640
CM
196
197 def __update_top_ref(self, ref):
262d31dc 198 git.set_ref(self.__top_ref, ref)
844a1640 199
64354a2d 200 def __update_log_ref(self, ref):
262d31dc 201 git.set_ref(self.__log_ref, ref)
64354a2d 202
54b09584 203 def get_old_bottom(self):
8762753a 204 return git.get_commit(self.get_old_top()).get_parent()
54b09584 205
41a6d859 206 def get_bottom(self):
8762753a 207 return git.get_commit(self.get_top()).get_parent()
41a6d859 208
54b09584 209 def get_old_top(self):
8fe7e9f0 210 return self._get_field('top.old')
54b09584 211
41a6d859 212 def get_top(self):
6b760799 213 return git.rev_parse(self.__top_ref)
41a6d859 214
7cc615f3 215 def set_top(self, value, backup = False):
41a6d859 216 if backup:
6b760799 217 curr = self.get_top()
8fe7e9f0 218 self._set_field('top.old', curr)
844a1640 219 self.__update_top_ref(value)
41a6d859
CM
220
221 def restore_old_boundaries(self):
8fe7e9f0 222 top = self._get_field('top.old')
41a6d859 223
8762753a 224 if top:
844a1640 225 self.__update_top_ref(top)
a5bbc44d 226 return True
41a6d859 227 else:
a5bbc44d 228 return False
41a6d859
CM
229
230 def get_description(self):
8fe7e9f0 231 return self._get_field('description', True)
41a6d859 232
7cc615f3 233 def set_description(self, line):
8fe7e9f0 234 self._set_field('description', line, True)
41a6d859
CM
235
236 def get_authname(self):
8fe7e9f0 237 return self._get_field('authname')
41a6d859 238
7cc615f3 239 def set_authname(self, name):
8fe7e9f0 240 self._set_field('authname', name or git.author().name)
41a6d859
CM
241
242 def get_authemail(self):
8fe7e9f0 243 return self._get_field('authemail')
41a6d859 244
9e3f506f 245 def set_authemail(self, email):
8fe7e9f0 246 self._set_field('authemail', email or git.author().email)
41a6d859
CM
247
248 def get_authdate(self):
ed60fdae
CM
249 date = self._get_field('authdate')
250 if not date:
251 return date
252
253 if re.match('[0-9]+\s+[+-][0-9]+', date):
254 # Unix time (seconds) + time zone
255 secs_tz = date.split()
256 date = formatdate(int(secs_tz[0]))[:-5] + secs_tz[1]
257
258 return date
41a6d859 259
4db741b1 260 def set_authdate(self, date):
8fe7e9f0 261 self._set_field('authdate', date or git.author().date)
41a6d859
CM
262
263 def get_commname(self):
8fe7e9f0 264 return self._get_field('commname')
41a6d859 265
7cc615f3 266 def set_commname(self, name):
8fe7e9f0 267 self._set_field('commname', name or git.committer().name)
41a6d859
CM
268
269 def get_commemail(self):
8fe7e9f0 270 return self._get_field('commemail')
41a6d859 271
9e3f506f 272 def set_commemail(self, email):
8fe7e9f0 273 self._set_field('commemail', email or git.committer().email)
41a6d859 274
64354a2d 275 def get_log(self):
8fe7e9f0 276 return self._get_field('log')
64354a2d
CM
277
278 def set_log(self, value, backup = False):
8fe7e9f0 279 self._set_field('log', value)
64354a2d
CM
280 self.__update_log_ref(value)
281
598e9d3f
KH
282# The current StGIT metadata format version.
283FORMAT_VERSION = 2
284
47e24a74 285class PatchSet(StgitObject):
dd1b8fcc
YD
286 def __init__(self, name = None):
287 try:
288 if name:
289 self.set_name (name)
290 else:
291 self.set_name (git.get_head_file())
292 self.__base_dir = basedir.get()
293 except git.GitException, ex:
294 raise StackException, 'GIT tree not initialised: %s' % ex
295
296 self._set_dir(os.path.join(self.__base_dir, 'patches', self.get_name()))
297
47e24a74
YD
298 def get_name(self):
299 return self.__name
300 def set_name(self, name):
301 self.__name = name
302
dd1b8fcc
YD
303 def _basedir(self):
304 return self.__base_dir
305
47e24a74
YD
306 def get_head(self):
307 """Return the head of the branch
308 """
309 crt = self.get_current_patch()
310 if crt:
311 return crt.get_top()
312 else:
313 return self.get_base()
314
315 def get_protected(self):
316 return os.path.isfile(os.path.join(self._dir(), 'protected'))
317
318 def protect(self):
319 protect_file = os.path.join(self._dir(), 'protected')
320 if not os.path.isfile(protect_file):
321 create_empty_file(protect_file)
322
323 def unprotect(self):
324 protect_file = os.path.join(self._dir(), 'protected')
325 if os.path.isfile(protect_file):
326 os.remove(protect_file)
327
328 def __branch_descr(self):
329 return 'branch.%s.description' % self.get_name()
330
331 def get_description(self):
332 return config.get(self.__branch_descr()) or ''
333
334 def set_description(self, line):
335 if line:
336 config.set(self.__branch_descr(), line)
337 else:
338 config.unset(self.__branch_descr())
339
340 def head_top_equal(self):
341 """Return true if the head and the top are the same
342 """
343 crt = self.get_current_patch()
344 if not crt:
345 # we don't care, no patches applied
346 return True
347 return git.get_head() == crt.get_top()
348
349 def is_initialised(self):
350 """Checks if series is already initialised
351 """
9171769c 352 return bool(config.get(self.format_version_key()))
47e24a74
YD
353
354
27827959 355def shortlog(patches):
1576d681 356 log = ''.join(Run('git', 'log', '--pretty=short',
27827959
KH
357 p.get_top(), '^%s' % p.get_bottom()).raw_output()
358 for p in patches)
1576d681 359 return Run('git', 'shortlog').raw_input(log).raw_output()
27827959 360
47e24a74 361class Series(PatchSet):
41a6d859
CM
362 """Class including the operations on series
363 """
364 def __init__(self, name = None):
40e65b92 365 """Takes a series name as the parameter.
41a6d859 366 """
dd1b8fcc 367 PatchSet.__init__(self, name)
598e9d3f
KH
368
369 # Update the branch to the latest format version if it is
370 # initialized, but don't touch it if it isn't.
9171769c 371 self.update_to_current_format_version()
598e9d3f 372
262d31dc 373 self.__refs_base = 'refs/patches/%s' % self.get_name()
02ac3ad2 374
8fe7e9f0
YD
375 self.__applied_file = os.path.join(self._dir(), 'applied')
376 self.__unapplied_file = os.path.join(self._dir(), 'unapplied')
841c7b2a 377 self.__hidden_file = os.path.join(self._dir(), 'hidden')
02ac3ad2
CL
378
379 # where this series keeps its patches
8fe7e9f0 380 self.__patch_dir = os.path.join(self._dir(), 'patches')
844a1640 381
ac50371b 382 # trash directory
8fe7e9f0 383 self.__trash_dir = os.path.join(self._dir(), 'trash')
ac50371b 384
9171769c 385 def format_version_key(self):
69ffa22e 386 return 'branch.%s.stgit.stackformatversion' % self.get_name()
9171769c
YD
387
388 def update_to_current_format_version(self):
389 """Update a potentially older StGIT directory structure to the
390 latest version. Note: This function should depend as little as
391 possible on external functions that may change during a format
392 version bump, since it must remain able to process older formats."""
393
dd1b8fcc 394 branch_dir = os.path.join(self._basedir(), 'patches', self.get_name())
9171769c
YD
395 def get_format_version():
396 """Return the integer format version number, or None if the
397 branch doesn't have any StGIT metadata at all, of any version."""
398 fv = config.get(self.format_version_key())
69ffa22e 399 ofv = config.get('branch.%s.stgitformatversion' % self.get_name())
9171769c
YD
400 if fv:
401 # Great, there's an explicitly recorded format version
402 # number, which means that the branch is initialized and
403 # of that exact version.
404 return int(fv)
69ffa22e
YD
405 elif ofv:
406 # Old name for the version info, upgrade it
407 config.set(self.format_version_key(), ofv)
408 config.unset('branch.%s.stgitformatversion' % self.get_name())
409 return int(ofv)
9171769c
YD
410 elif os.path.isdir(os.path.join(branch_dir, 'patches')):
411 # There's a .git/patches/<branch>/patches dirctory, which
412 # means this is an initialized version 1 branch.
413 return 1
414 elif os.path.isdir(branch_dir):
415 # There's a .git/patches/<branch> directory, which means
416 # this is an initialized version 0 branch.
417 return 0
418 else:
419 # The branch doesn't seem to be initialized at all.
420 return None
421 def set_format_version(v):
422 out.info('Upgraded branch %s to format version %d' % (self.get_name(), v))
423 config.set(self.format_version_key(), '%d' % v)
424 def mkdir(d):
425 if not os.path.isdir(d):
426 os.makedirs(d)
427 def rm(f):
428 if os.path.exists(f):
429 os.remove(f)
262d31dc
KH
430 def rm_ref(ref):
431 if git.ref_exists(ref):
432 git.delete_ref(ref)
9171769c
YD
433
434 # Update 0 -> 1.
435 if get_format_version() == 0:
436 mkdir(os.path.join(branch_dir, 'trash'))
437 patch_dir = os.path.join(branch_dir, 'patches')
438 mkdir(patch_dir)
262d31dc 439 refs_base = 'refs/patches/%s' % self.get_name()
9171769c
YD
440 for patch in (file(os.path.join(branch_dir, 'unapplied')).readlines()
441 + file(os.path.join(branch_dir, 'applied')).readlines()):
442 patch = patch.strip()
443 os.rename(os.path.join(branch_dir, patch),
444 os.path.join(patch_dir, patch))
6b760799
DK
445 topfield = os.path.join(patch_dir, patch, 'top')
446 if os.path.isfile(topfield):
447 top = read_string(topfield, False)
448 else:
449 top = None
450 if top:
451 git.set_ref(refs_base + '/' + patch, top)
9171769c
YD
452 set_format_version(1)
453
454 # Update 1 -> 2.
455 if get_format_version() == 1:
456 desc_file = os.path.join(branch_dir, 'description')
457 if os.path.isfile(desc_file):
458 desc = read_string(desc_file)
459 if desc:
460 config.set('branch.%s.description' % self.get_name(), desc)
461 rm(desc_file)
462 rm(os.path.join(branch_dir, 'current'))
262d31dc 463 rm_ref('refs/bases/%s' % self.get_name())
9171769c
YD
464 set_format_version(2)
465
466 # Make sure we're at the latest version.
467 if not get_format_version() in [None, FORMAT_VERSION]:
468 raise StackException('Branch %s is at format version %d, expected %d'
469 % (self.get_name(), get_format_version(), FORMAT_VERSION))
470
c1e4d7e0
CM
471 def __patch_name_valid(self, name):
472 """Raise an exception if the patch name is not valid.
473 """
474 if not name or re.search('[^\w.-]', name):
475 raise StackException, 'Invalid patch name: "%s"' % name
476
41a6d859
CM
477 def get_patch(self, name):
478 """Return a Patch object for the given name
479 """
262d31dc 480 return Patch(name, self.__patch_dir, self.__refs_base)
41a6d859 481
4d0ba818
KH
482 def get_current_patch(self):
483 """Return a Patch object representing the topmost patch, or
484 None if there is no such patch."""
485 crt = self.get_current()
486 if not crt:
487 return None
4c0dd299 488 return self.get_patch(crt)
4d0ba818 489
41a6d859 490 def get_current(self):
4d0ba818
KH
491 """Return the name of the topmost patch, or None if there is
492 no such patch."""
532cdf94
KH
493 try:
494 applied = self.get_applied()
495 except StackException:
496 # No "applied" file: branch is not initialized.
497 return None
498 try:
499 return applied[-1]
500 except IndexError:
501 # No patches applied.
41a6d859 502 return None
41a6d859
CM
503
504 def get_applied(self):
40e65b92 505 if not os.path.isfile(self.__applied_file):
d37ff079 506 raise StackException, 'Branch "%s" not initialised' % self.get_name()
17364282 507 return read_strings(self.__applied_file)
41a6d859 508
ca216016
KH
509 def set_applied(self, applied):
510 write_strings(self.__applied_file, applied)
511
41a6d859 512 def get_unapplied(self):
40e65b92 513 if not os.path.isfile(self.__unapplied_file):
d37ff079 514 raise StackException, 'Branch "%s" not initialised' % self.get_name()
17364282 515 return read_strings(self.__unapplied_file)
41a6d859 516
ca216016
KH
517 def set_unapplied(self, unapplied):
518 write_strings(self.__unapplied_file, unapplied)
519
841c7b2a
CM
520 def get_hidden(self):
521 if not os.path.isfile(self.__hidden_file):
522 return []
17364282 523 return read_strings(self.__hidden_file)
841c7b2a 524
ba66e579 525 def get_base(self):
16d69115
KH
526 # Return the parent of the bottommost patch, if there is one.
527 if os.path.isfile(self.__applied_file):
528 bottommost = file(self.__applied_file).readline().strip()
529 if bottommost:
530 return self.get_patch(bottommost).get_bottom()
531 # No bottommost patch, so just return HEAD
532 return git.get_head()
ba66e579 533
254d99f8 534 def get_parent_remote(self):
d37ff079 535 value = config.get('branch.%s.remote' % self.get_name())
f72ad3d6
YD
536 if value:
537 return value
538 elif 'origin' in git.remotes_list():
27ac2b7e 539 out.note(('No parent remote declared for stack "%s",'
d37ff079 540 ' defaulting to "origin".' % self.get_name()),
27ac2b7e 541 ('Consider setting "branch.%s.remote" and'
82792b45 542 ' "branch.%s.merge" with "git config".'
d37ff079 543 % (self.get_name(), self.get_name())))
f72ad3d6
YD
544 return 'origin'
545 else:
d37ff079 546 raise StackException, 'Cannot find a parent remote for "%s"' % self.get_name()
254d99f8
YD
547
548 def __set_parent_remote(self, remote):
d37ff079 549 value = config.set('branch.%s.remote' % self.get_name(), remote)
254d99f8 550
8866feda 551 def get_parent_branch(self):
d37ff079 552 value = config.get('branch.%s.stgit.parentbranch' % self.get_name())
8866feda
YD
553 if value:
554 return value
555 elif git.rev_parse('heads/origin'):
27ac2b7e 556 out.note(('No parent branch declared for stack "%s",'
d37ff079 557 ' defaulting to "heads/origin".' % self.get_name()),
27ac2b7e 558 ('Consider setting "branch.%s.stgit.parentbranch"'
82792b45 559 ' with "git config".' % self.get_name()))
8866feda
YD
560 return 'heads/origin'
561 else:
d37ff079 562 raise StackException, 'Cannot find a parent branch for "%s"' % self.get_name()
8866feda
YD
563
564 def __set_parent_branch(self, name):
d37ff079 565 if config.get('branch.%s.remote' % self.get_name()):
4646e7a3
YD
566 # Never set merge if remote is not set to avoid
567 # possibly-erroneous lookups into 'origin'
d37ff079
YD
568 config.set('branch.%s.merge' % self.get_name(), name)
569 config.set('branch.%s.stgit.parentbranch' % self.get_name(), name)
8866feda
YD
570
571 def set_parent(self, remote, localbranch):
572 if localbranch:
16881517
KH
573 if remote:
574 self.__set_parent_remote(remote)
8866feda 575 self.__set_parent_branch(localbranch)
4646e7a3
YD
576 # We'll enforce this later
577# else:
d37ff079 578# raise StackException, 'Parent branch (%s) should be specified for %s' % localbranch, self.get_name()
8866feda 579
41a6d859 580 def __patch_is_current(self, patch):
8fe7e9f0 581 return patch.get_name() == self.get_current()
41a6d859 582
ed0350be 583 def patch_applied(self, name):
41a6d859
CM
584 """Return true if the patch exists in the applied list
585 """
586 return name in self.get_applied()
587
ed0350be 588 def patch_unapplied(self, name):
41a6d859
CM
589 """Return true if the patch exists in the unapplied list
590 """
591 return name in self.get_unapplied()
592
841c7b2a
CM
593 def patch_hidden(self, name):
594 """Return true if the patch is hidden.
595 """
596 return name in self.get_hidden()
597
4d0ba818
KH
598 def patch_exists(self, name):
599 """Return true if there is a patch with the given name, false
600 otherwise."""
ca8b854c
CM
601 return self.patch_applied(name) or self.patch_unapplied(name) \
602 or self.patch_hidden(name)
4d0ba818 603
8866feda 604 def init(self, create_at=False, parent_remote=None, parent_branch=None):
41a6d859
CM
605 """Initialises the stgit series
606 """
598e9d3f 607 if self.is_initialised():
d37ff079 608 raise StackException, '%s already initialized' % self.get_name()
262d31dc 609 for d in [self._dir()]:
598e9d3f
KH
610 if os.path.exists(d):
611 raise StackException, '%s already exists' % d
fe847176 612
a22a62b6 613 if (create_at!=False):
d37ff079 614 git.create_branch(self.get_name(), create_at)
a22a62b6 615
41a6d859
CM
616 os.makedirs(self.__patch_dir)
617
8866feda 618 self.set_parent(parent_remote, parent_branch)
41a6d859 619
8fe7e9f0
YD
620 self.create_empty_field('applied')
621 self.create_empty_field('unapplied')
41a6d859 622
9171769c 623 config.set(self.format_version_key(), str(FORMAT_VERSION))
bad9dcfc 624
660ba985
CL
625 def rename(self, to_name):
626 """Renames a series
627 """
628 to_stack = Series(to_name)
84bf6268
CL
629
630 if to_stack.is_initialised():
d37ff079 631 raise StackException, '"%s" already exists' % to_stack.get_name()
660ba985 632
262d31dc
KH
633 patches = self.get_applied() + self.get_unapplied()
634
d37ff079 635 git.rename_branch(self.get_name(), to_name)
660ba985 636
262d31dc
KH
637 for patch in patches:
638 git.rename_ref('refs/patches/%s/%s' % (self.get_name(), patch),
639 'refs/patches/%s/%s' % (to_name, patch))
640 git.rename_ref('refs/patches/%s/%s.log' % (self.get_name(), patch),
641 'refs/patches/%s/%s.log' % (to_name, patch))
8fe7e9f0 642 if os.path.isdir(self._dir()):
dd1b8fcc 643 rename(os.path.join(self._basedir(), 'patches'),
d37ff079 644 self.get_name(), to_stack.get_name())
660ba985 645
cb5be4c3 646 # Rename the config section
337a0743
KH
647 for k in ['branch.%s', 'branch.%s.stgit']:
648 config.rename_section(k % self.get_name(), k % to_name)
cb5be4c3 649
660ba985
CL
650 self.__init__(to_name)
651
cc3db2b1
CL
652 def clone(self, target_series):
653 """Clones a series
654 """
09d8f8c5
CM
655 try:
656 # allow cloning of branches not under StGIT control
ba66e579 657 base = self.get_base()
09d8f8c5
CM
658 except:
659 base = git.get_head()
a22a62b6 660 Series(target_series).init(create_at = base)
cc3db2b1
CL
661 new_series = Series(target_series)
662
663 # generate an artificial description file
d37ff079 664 new_series.set_description('clone of "%s"' % self.get_name())
cc3db2b1
CL
665
666 # clone self's entire series as unapplied patches
09d8f8c5
CM
667 try:
668 # allow cloning of branches not under StGIT control
669 applied = self.get_applied()
670 unapplied = self.get_unapplied()
671 patches = applied + unapplied
672 patches.reverse()
673 except:
674 patches = applied = unapplied = []
cc3db2b1
CL
675 for p in patches:
676 patch = self.get_patch(p)
8fce9909
YD
677 newpatch = new_series.new_patch(p, message = patch.get_description(),
678 can_edit = False, unapplied = True,
679 bottom = patch.get_bottom(),
680 top = patch.get_top(),
681 author_name = patch.get_authname(),
682 author_email = patch.get_authemail(),
683 author_date = patch.get_authdate())
684 if patch.get_log():
27ac2b7e 685 out.info('Setting log to %s' % patch.get_log())
8fce9909
YD
686 newpatch.set_log(patch.get_log())
687 else:
27ac2b7e 688 out.info('No log for %s' % p)
cc3db2b1
CL
689
690 # fast forward the cloned series to self's top
09d8f8c5 691 new_series.forward_patches(applied)
cc3db2b1 692
f32cdac5 693 # Clone parent informations
d37ff079 694 value = config.get('branch.%s.remote' % self.get_name())
0579dae6
PR
695 if value:
696 config.set('branch.%s.remote' % target_series, value)
697
d37ff079 698 value = config.get('branch.%s.merge' % self.get_name())
0579dae6
PR
699 if value:
700 config.set('branch.%s.merge' % target_series, value)
701
d37ff079 702 value = config.get('branch.%s.stgit.parentbranch' % self.get_name())
f32cdac5
YD
703 if value:
704 config.set('branch.%s.stgit.parentbranch' % target_series, value)
705
fc804a49
CL
706 def delete(self, force = False):
707 """Deletes an stgit series
708 """
2d00440c 709 if self.is_initialised():
fc804a49
CL
710 patches = self.get_unapplied() + self.get_applied()
711 if not force and patches:
712 raise StackException, \
713 'Cannot delete: the series still contains patches'
fc804a49 714 for p in patches:
4c0dd299 715 self.get_patch(p).delete()
fc804a49 716
c177ec71
YD
717 # remove the trash directory if any
718 if os.path.exists(self.__trash_dir):
719 for fname in os.listdir(self.__trash_dir):
720 os.remove(os.path.join(self.__trash_dir, fname))
721 os.rmdir(self.__trash_dir)
ac50371b 722
8fe7e9f0 723 # FIXME: find a way to get rid of those manual removals
a9d090f4 724 # (move functionality to StgitObject ?)
84bf6268 725 if os.path.exists(self.__applied_file):
fc804a49 726 os.remove(self.__applied_file)
84bf6268 727 if os.path.exists(self.__unapplied_file):
fc804a49 728 os.remove(self.__unapplied_file)
841c7b2a
CM
729 if os.path.exists(self.__hidden_file):
730 os.remove(self.__hidden_file)
f9072c2f
YD
731 if os.path.exists(self._dir()+'/orig-base'):
732 os.remove(self._dir()+'/orig-base')
737f3549 733
fc804a49
CL
734 if not os.listdir(self.__patch_dir):
735 os.rmdir(self.__patch_dir)
736 else:
27ac2b7e 737 out.warn('Patch directory %s is not empty' % self.__patch_dir)
737f3549 738
c7728cd5 739 try:
737f3549 740 os.removedirs(self._dir())
c7728cd5 741 except OSError:
27ac2b7e
KH
742 raise StackException('Series directory %s is not empty'
743 % self._dir())
737f3549 744
ff432158
CM
745 try:
746 git.delete_branch(self.get_name())
747 except GitException:
748 out.warn('Could not delete branch "%s"' % self.get_name())
fc804a49 749
9a6bcbe2
KH
750 config.remove_section('branch.%s' % self.get_name())
751 config.remove_section('branch.%s.stgit' % self.get_name())
85289c08 752
026c0689
CM
753 def refresh_patch(self, files = None, message = None, edit = False,
754 show_patch = False,
6ad48e48 755 cache_update = True,
41a6d859
CM
756 author_name = None, author_email = None,
757 author_date = None,
f80bef49 758 committer_name = None, committer_email = None,
cb688601 759 backup = True, sign_str = None, log = 'refresh',
6889c93c 760 notes = None, bottom = None):
692c15ef 761 """Generates a new commit for the topmost patch
41a6d859 762 """
692c15ef
DK
763 patch = self.get_current_patch()
764 if not patch:
41a6d859
CM
765 raise StackException, 'No patches applied'
766
41a6d859
CM
767 descr = patch.get_description()
768 if not (message or descr):
769 edit = True
770 descr = ''
771 elif message:
772 descr = message
773
ed60fdae
CM
774 # TODO: move this out of the stgit.stack module, it is really
775 # for higher level commands to handle the user interaction
41a6d859 776 if not message and edit:
6ad48e48 777 descr = edit_file(self, descr.rstrip(), \
41a6d859 778 'Please edit the description for patch "%s" ' \
692c15ef 779 'above.' % patch.get_name(), show_patch)
41a6d859
CM
780
781 if not author_name:
782 author_name = patch.get_authname()
783 if not author_email:
784 author_email = patch.get_authemail()
785 if not author_date:
786 author_date = patch.get_authdate()
787 if not committer_name:
788 committer_name = patch.get_commname()
789 if not committer_email:
790 committer_email = patch.get_commemail()
791
130df01a 792 descr = add_sign_line(descr, sign_str, committer_name, committer_email)
c40c3500 793
6889c93c
DK
794 if not bottom:
795 bottom = patch.get_bottom()
f80bef49 796
026c0689 797 commit_id = git.commit(files = files,
f80bef49 798 message = descr, parents = [bottom],
402ad990 799 cache_update = cache_update,
41a6d859
CM
800 allowempty = True,
801 author_name = author_name,
802 author_email = author_email,
803 author_date = author_date,
804 committer_name = committer_name,
805 committer_email = committer_email)
806
f80bef49 807 patch.set_top(commit_id, backup = backup)
84fcbc3b
CM
808 patch.set_description(descr)
809 patch.set_authname(author_name)
810 patch.set_authemail(author_email)
811 patch.set_authdate(author_date)
812 patch.set_commname(committer_name)
813 patch.set_commemail(committer_email)
c14444b9 814
64354a2d 815 if log:
eff17c6b 816 self.log_patch(patch, log, notes)
64354a2d 817
c14444b9 818 return commit_id
41a6d859 819
f80bef49
CM
820 def undo_refresh(self):
821 """Undo the patch boundaries changes caused by 'refresh'
822 """
823 name = self.get_current()
824 assert(name)
825
4c0dd299 826 patch = self.get_patch(name)
f80bef49
CM
827 old_bottom = patch.get_old_bottom()
828 old_top = patch.get_old_top()
829
830 # the bottom of the patch is not changed by refresh. If the
831 # old_bottom is different, there wasn't any previous 'refresh'
832 # command (probably only a 'push')
833 if old_bottom != patch.get_bottom() or old_top == patch.get_top():
06848fab 834 raise StackException, 'No undo information available'
f80bef49
CM
835
836 git.reset(tree_id = old_top, check_out = False)
64354a2d
CM
837 if patch.restore_old_boundaries():
838 self.log_patch(patch, 'undo')
f80bef49 839
37a4d1bf
CM
840 def new_patch(self, name, message = None, can_edit = True,
841 unapplied = False, show_patch = False,
0ec93bfd 842 top = None, bottom = None, commit = True,
41a6d859 843 author_name = None, author_email = None, author_date = None,