3
from patches import parse_patches
9
from bzrlib.commands import Command
10
from bzrlib.branch import Branch
11
from bzrlib import DEFAULT_IGNORE
12
from hunk_selector import HunkSelector
13
from diffstat import DiffStat
14
from subprocess import Popen, PIPE
16
DEFAULT_IGNORE.append('./.bzr-shelf*')
18
class QuitException(Exception):
3
from datetime import datetime
4
from errors import CommandError, PatchFailed
5
from hunk_selector import ShelveHunkSelector, UnshelveHunkSelector
6
from patch import run_patch
7
from patchsource import FilePatchSource
8
from bzrlib.osutils import rename
21
10
class Shelf(object):
22
def __init__(self, location):
23
self.branch = Branch.open_containing(location)[0]
25
def shelf_suffix(self, index):
35
yield self.shelf_suffix(i)
38
stem = os.path.join(self.branch.base, '.bzr-shelf')
39
for end in name_sequence():
41
if not os.path.exists(name):
45
stem = os.path.join(self.branch.base, '.bzr-shelf')
46
shelves = glob.glob(stem)
47
shelves.extend(glob.glob(stem + '-*'))
48
def shelf_index(name):
11
MESSAGE_PREFIX = "# Shelved patch: "
15
'shelves' : '.shelf/shelves',
16
'current-shelf' : '.shelf/current-shelf',
19
def __init__(self, base, name=None):
24
current = os.path.join(self.base, self._paths['current-shelf'])
25
name = open(current).read().strip()
27
assert '\n' not in name
30
self.dir = os.path.join(self.base, self._paths['shelves'], name)
31
if not os.path.isdir(self.dir):
35
# Create required directories etc.
36
for dir in [self._paths['base'], self._paths['shelves']]:
37
dir = os.path.join(self.base, dir)
38
if not os.path.isdir(dir):
41
current = os.path.join(self.base, self._paths['current-shelf'])
42
if not os.path.exists(current):
43
f = open(current, 'w')
47
def make_default(self):
48
f = open(os.path.join(self.base, self._paths['current-shelf']), 'w')
51
self.log("Default shelf is now '%s'\n" % self.name)
56
def delete(self, patch):
57
path = self.__path_from_user(patch)
58
rename(path, '%s~' % path)
60
def display(self, patch=None):
62
path = self.last_patch()
64
raise CommandError("No patches on shelf.")
66
path = self.__path_from_user(patch)
67
sys.stdout.write(open(path).read())
70
indexes = self.__list()
71
self.log("Patches on shelf '%s':" % self.name)
77
msg = self.get_patch_message(self.__path(index))
79
msg = "No message saved with patch."
80
self.log(' %.2d: %s\n' % (index, msg))
82
def __path_from_user(self, patch_id):
84
patch_index = int(patch_id)
85
except (TypeError, ValueError):
86
raise CommandError("Invalid patch name '%s'" % patch_id)
88
path = self.__path(patch_index)
90
if not os.path.exists(path):
91
raise CommandError("Patch '%s' doesn't exist on shelf %s!" % \
92
(patch_id, self.name))
96
def __path(self, index):
97
return os.path.join(self.dir, '%.2d' % index)
100
indexes = self.__list()
102
if len(indexes) == 0:
105
next = indexes[-1] + 1
106
return self.__path(next)
109
patches = os.listdir(self.dir)
113
continue # ignore backup files
115
indexes.append(int(f))
117
self.log("Warning: Ignoring junk file '%s' on shelf.\n" % f)
122
def last_patch(self):
123
indexes = self.__list()
125
if len(indexes) == 0:
128
return self.__path(indexes[-1])
130
def get_patch_message(self, patch_path):
131
patch = open(patch_path, 'r').read()
133
if not patch.startswith(self.MESSAGE_PREFIX):
135
return patch[len(self.MESSAGE_PREFIX):patch.index('\n')]
137
def unshelve(self, patch_source, patch_name=None, all=False, force=False,
139
self._check_upgrade()
141
if no_color is False:
145
if patch_name is None:
146
patch_path = self.last_patch()
148
patch_path = self.__path_from_user(patch_name)
150
if patch_path is None:
151
raise CommandError("No patch found on shelf %s" % self.name)
153
patches = FilePatchSource(patch_path).readpatches()
155
to_unshelve = patches
158
hs = UnshelveHunkSelector(patches, color)
159
to_unshelve, to_remain = hs.select()
161
if len(to_unshelve) == 0:
162
raise CommandError('Nothing to unshelve')
164
message = self.get_patch_message(patch_path)
166
message = "No message saved with patch."
167
self.log('Unshelving from %s/%s: "%s"\n' % \
168
(self.name, os.path.basename(patch_path), message))
171
self._run_patch(to_unshelve, dry_run=True)
172
self._run_patch(to_unshelve)
175
self._run_patch(to_unshelve, strip=1, dry_run=True)
176
self._run_patch(to_unshelve, strip=1)
179
self.log('Warning: Unshelving failed, forcing as ' \
180
'requested. Shelf will not be modified.\n')
182
self._run_patch(to_unshelve)
186
raise CommandError("Your shelved patch no " \
187
"longer applies cleanly to the working tree!")
189
# Backup the shelved patch
190
rename(patch_path, '%s~' % patch_path)
192
if len(to_remain) > 0:
193
f = open(patch_path, 'w')
194
for patch in to_remain:
198
def shelve(self, patch_source, all=False, message=None, no_color=False):
199
self._check_upgrade()
200
if no_color is False:
205
patches = patch_source.readpatches()
210
to_shelve = ShelveHunkSelector(patches, color).select()[0]
212
if len(to_shelve) == 0:
213
raise CommandError('Nothing to shelve')
216
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
217
message = "Changes shelved on %s" % timestamp
219
patch_path = self.next_patch()
220
self.log('Shelving to %s/%s: "%s"\n' % \
221
(self.name, os.path.basename(patch_path), message))
223
f = open(patch_path, 'a')
225
assert '\n' not in message
226
f.write("%s%s\n" % (self.MESSAGE_PREFIX, message))
228
for patch in to_shelve:
236
self._run_patch(to_shelve, reverse=True, dry_run=True)
237
self._run_patch(to_shelve, reverse=True)
240
self._run_patch(to_shelve, reverse=True, strip=1, dry_run=True)
241
self._run_patch(to_shelve, reverse=True, strip=1)
243
raise CommandError("Failed removing shelved changes from the"
246
def _run_patch(self, patches, strip=0, reverse=False, dry_run=False):
247
run_patch(self.base, patches, strip, reverse, dry_run)
249
def _check_upgrade(self):
250
if len(self._list_old_shelves()) > 0:
251
raise CommandError("Old format shelves found, either upgrade " \
254
def _list_old_shelves(self):
256
stem = os.path.join(self.base, '.bzr-shelf')
258
patches = glob.glob(stem)
259
patches.extend(glob.glob(stem + '-*[!~]'))
261
if len(patches) == 0:
264
def patch_index(name):
51
return int(name[len(stem)+1:])
52
shelvenums = [shelf_index(f) for f in shelves]
55
if len(shelvenums) == 0:
57
return stem + self.shelf_suffix(shelvenums[-1])
59
def get_shelf_message(self, shelf):
61
if not shelf.startswith(prefix):
63
return shelf[len(prefix):shelf.index('\n')]
66
shelf = self.last_shelf()
69
raise Exception("No shelf found in '%s'" % self.branch.base)
71
patch = open(shelf, 'r').read()
73
print >>sys.stderr, "Reapplying shelved patches",
74
message = self.get_shelf_message(patch)
75
if message is not None:
76
print >>sys.stderr, ' "%s"' % message
78
print >>sys.stderr, ""
79
run_patch(self.branch.base, (patch,))
82
diff_stat = DiffStat(self.get_patches(None, None))
83
print 'Diff status is now:\n', diff_stat
87
def get_patches(self, revision, file_list):
88
from StringIO import StringIO
89
from bzrlib.diff import show_diff
91
show_diff(self.branch, revision, specific_files=file_list, output=out)
93
return out.readlines()
95
def shelve(self, all_hunks=False, message=None, revision=None,
97
patches = parse_patches(self.get_patches(revision, file_list))
101
patches = HunkSelector(patches).select()
102
except QuitException:
267
return int(name[len(stem) + 1:])
269
# patches might not be sorted in the right order
271
for patch in patches:
275
patch_ids.append(int(patch[len(stem) + 1:]))
284
patches.append('%s-%s' % (stem, id))
289
patches = self._list_old_shelves()
105
291
if len(patches) == 0:
106
print >>sys.stderr, 'Nothing to shelve'
292
self.log('No old-style shelves found to upgrade.\n')
109
shelf = self.next_shelf()
110
print >>sys.stderr, "Saving shelved patches to", shelf
111
shelf = open(shelf, 'a')
112
if message is not None:
113
assert '\n' not in message
114
shelf.write("# shelf: %s\n" % message)
115
295
for patch in patches:
116
shelf.write(str(patch))
119
os.fsync(shelf.fileno())
122
print >>sys.stderr, "Reverting shelved patches"
123
run_patch(self.branch.base, patches, reverse=True)
125
diff_stat = DiffStat(self.get_patches(None, None))
126
print 'Diff status is now:\n', diff_stat
130
def run_patch(branch_base, patches, reverse=False):
131
args = ['patch', '-d', branch_base, '-s', '-p0', '-f']
134
process = Popen(args, stdin=PIPE)
135
for patch in patches:
136
process.stdin.write(str(patch))
137
process.stdin.close()
138
result = process.wait()
139
if result not in (0, 1):
140
raise Exception("Error applying patches")
296
old_file = open(patch, 'r')
297
new_path = self.next_patch()
298
new_file = open(new_path, 'w')
299
new_file.write(old_file.read())
302
self.log('Copied %s to %s/%s\n' % (os.path.basename(patch),
303
self.name, os.path.basename(new_path)))
304
rename(patch, patch + '~')