6
from datetime import datetime
7
from errors import CommandError, PatchFailed
8
from hunk_selector import ShelveHunkSelector, UnshelveHunkSelector
9
from patchsource import PatchSource, FilePatchSource
12
MESSAGE_PREFIX = "# Shelved patch: "
16
'shelves' : '.shelf/shelves',
17
'current-shelf' : '.shelf/current-shelf',
20
def __init__(self, base, name=None):
25
current = os.path.join(self.base, self._paths['current-shelf'])
26
name = open(current).read().strip()
28
assert '\n' not in name
31
self.dir = os.path.join(self.base, self._paths['shelves'], name)
32
if not os.path.isdir(self.dir):
36
# Create required directories etc.
37
for dir in [self._paths['base'], self._paths['shelves']]:
38
dir = os.path.join(self.base, dir)
39
if not os.path.isdir(dir):
42
current = os.path.join(self.base, self._paths['current-shelf'])
43
if not os.path.exists(current):
44
f = open(current, 'w')
48
def make_default(self):
49
f = open(os.path.join(self.base, self._paths['current-shelf']), 'w')
52
self.log("Default shelf is now '%s'\n" % self.name)
57
def delete(self, patch):
58
path = self.__path_from_user(patch)
59
os.rename(path, '%s~' % path)
61
def display(self, patch=None):
63
path = self.last_patch()
65
path = self.__path_from_user(patch)
66
sys.stdout.write(open(path).read())
69
indexes = self.__list()
70
self.log("Patches on shelf '%s':" % self.name)
76
msg = self.get_patch_message(self.__path(index))
78
msg = "No message saved with patch."
79
self.log(' %.2d: %s\n' % (index, msg))
81
def __path_from_user(self, patch_id):
83
patch_index = int(patch_id)
84
except (TypeError, ValueError):
85
raise CommandError("Invalid patch name '%s'" % patch_id)
87
path = self.__path(patch_index)
89
if not os.path.exists(path):
90
raise CommandError("Patch '%s' doesn't exist on shelf %s!" % \
91
(patch_id, self.name))
95
def __path(self, index):
96
return os.path.join(self.dir, '%.2d' % index)
99
indexes = self.__list()
101
if len(indexes) == 0:
104
next = indexes[-1] + 1
105
return self.__path(next)
108
patches = os.listdir(self.dir)
112
continue # ignore backup files
114
indexes.append(int(f))
116
self.log("Warning: Ignoring junk file '%s' on shelf.\n" % f)
121
def last_patch(self):
122
indexes = self.__list()
124
if len(indexes) == 0:
127
return self.__path(indexes[-1])
129
def get_patch_message(self, patch_path):
130
patch = open(patch_path, 'r').read()
132
if not patch.startswith(self.MESSAGE_PREFIX):
134
return patch[len(self.MESSAGE_PREFIX):patch.index('\n')]
136
def unshelve(self, patch_source, patch_name=None, all=False, force=False):
137
self._check_upgrade()
139
if patch_name is None:
140
patch_path = self.last_patch()
142
patch_path = self.__path_from_user(patch_name)
144
if patch_path is None:
145
raise CommandError("No patch found on shelf %s" % self.name)
147
patches = FilePatchSource(patch_path).readpatches()
149
to_unshelve = patches
152
to_unshelve, to_remain = UnshelveHunkSelector(patches).select()
154
if len(to_unshelve) == 0:
155
raise CommandError('Nothing to unshelve')
157
message = self.get_patch_message(patch_path)
159
message = "No message saved with patch."
160
self.log('Unshelving from %s/%s: "%s"\n' % \
161
(self.name, os.path.basename(patch_path), message))
164
self._run_patch(to_unshelve, dry_run=True)
165
self._run_patch(to_unshelve)
168
self._run_patch(to_unshelve, strip=1, dry_run=True)
169
self._run_patch(to_unshelve, strip=1)
172
self.log('Warning: Unshelving failed, forcing as ' \
173
'requested. Shelf will not be modified.\n')
175
self._run_patch(to_unshelve)
179
raise CommandError("Your shelved patch no " \
180
"longer applies cleanly to the working tree!")
182
# Backup the shelved patch
183
os.rename(patch_path, '%s~' % patch_path)
185
if len(to_remain) > 0:
186
f = open(patch_path, 'w')
187
for patch in to_remain:
191
def shelve(self, patch_source, all=False, message=None):
192
self._check_upgrade()
194
patches = patch_source.readpatches()
199
to_shelve = ShelveHunkSelector(patches).select()[0]
201
if len(to_shelve) == 0:
202
raise CommandError('Nothing to shelve')
205
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
206
message = "Changes shelved on %s" % timestamp
208
patch_path = self.next_patch()
209
self.log('Shelving to %s/%s: "%s"\n' % \
210
(self.name, os.path.basename(patch_path), message))
212
f = open(patch_path, 'a')
214
assert '\n' not in message
215
f.write("%s%s\n" % (self.MESSAGE_PREFIX, message))
217
for patch in to_shelve:
225
self._run_patch(to_shelve, reverse=True, dry_run=True)
226
self._run_patch(to_shelve, reverse=True)
229
self._run_patch(to_shelve, reverse=True, strip=1, dry_run=True)
230
self._run_patch(to_shelve, reverse=True, strip=1)
232
raise CommandError("Failed removing shelved changes from the"
235
def _run_patch(self, patches, strip=0, reverse=False, dry_run=False):
236
args = ['patch', '-d', self.base, '-s', '-p%d' % strip, '-f']
240
args.append('--dry-run')
241
stdout = stderr = subprocess.PIPE
243
stdout = stderr = None
245
process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=stdout,
247
for patch in patches:
248
process.stdin.write(str(patch))
250
process.communicate()
252
result = process.wait()
258
def _check_upgrade(self):
259
if len(self._list_old_shelves()) > 0:
260
raise CommandError("Old format shelves found, either upgrade " \
263
def _list_old_shelves(self):
265
stem = os.path.join(self.base, '.bzr-shelf')
267
patches = glob.glob(stem)
268
patches.extend(glob.glob(stem + '-*[!~]'))
270
if len(patches) == 0:
273
def patch_index(name):
276
return int(name[len(stem) + 1:])
278
# patches might not be sorted in the right order
280
for patch in patches:
284
patch_ids.append(int(patch[len(stem) + 1:]))
293
patches.append('%s-%s' % (stem, id))
298
patches = self._list_old_shelves()
300
if len(patches) == 0:
301
self.log('No old-style shelves found to upgrade.\n')
304
for patch in patches:
305
old_file = open(patch, 'r')
306
new_path = self.next_patch()
307
new_file = open(new_path, 'w')
308
new_file.write(old_file.read())
311
self.log('Copied %s to %s/%s\n' % (os.path.basename(patch),
312
self.name, os.path.basename(new_path)))
313
os.rename(patch, patch + '~')