6
from datetime import datetime
7
from errors import CommandError, PatchFailed
8
from hunk_selector import ShelveHunkSelector, UnshelveHunkSelector
9
from patchsource import PatchSource, FilePatchSource
10
from bzrlib.osutils import rename
13
MESSAGE_PREFIX = "# Shelved patch: "
17
'shelves' : '.shelf/shelves',
18
'current-shelf' : '.shelf/current-shelf',
21
def __init__(self, base, name=None):
26
current = os.path.join(self.base, self._paths['current-shelf'])
27
name = open(current).read().strip()
29
assert '\n' not in name
32
self.dir = os.path.join(self.base, self._paths['shelves'], name)
33
if not os.path.isdir(self.dir):
37
# Create required directories etc.
38
for dir in [self._paths['base'], self._paths['shelves']]:
39
dir = os.path.join(self.base, dir)
40
if not os.path.isdir(dir):
43
current = os.path.join(self.base, self._paths['current-shelf'])
44
if not os.path.exists(current):
45
f = open(current, 'w')
49
def make_default(self):
50
f = open(os.path.join(self.base, self._paths['current-shelf']), 'w')
53
self.log("Default shelf is now '%s'\n" % self.name)
58
def delete(self, patch):
59
path = self.__path_from_user(patch)
60
rename(path, '%s~' % path)
62
def display(self, patch=None):
64
path = self.last_patch()
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):
138
self._check_upgrade()
140
if patch_name is None:
141
patch_path = self.last_patch()
143
patch_path = self.__path_from_user(patch_name)
145
if patch_path is None:
146
raise CommandError("No patch found on shelf %s" % self.name)
148
patches = FilePatchSource(patch_path).readpatches()
150
to_unshelve = patches
153
to_unshelve, to_remain = UnshelveHunkSelector(patches).select()
155
if len(to_unshelve) == 0:
156
raise CommandError('Nothing to unshelve')
158
message = self.get_patch_message(patch_path)
160
message = "No message saved with patch."
161
self.log('Unshelving from %s/%s: "%s"\n' % \
162
(self.name, os.path.basename(patch_path), message))
165
self._run_patch(to_unshelve, dry_run=True)
166
self._run_patch(to_unshelve)
169
self._run_patch(to_unshelve, strip=1, dry_run=True)
170
self._run_patch(to_unshelve, strip=1)
173
self.log('Warning: Unshelving failed, forcing as ' \
174
'requested. Shelf will not be modified.\n')
176
self._run_patch(to_unshelve)
180
raise CommandError("Your shelved patch no " \
181
"longer applies cleanly to the working tree!")
183
# Backup the shelved patch
184
rename(patch_path, '%s~' % patch_path)
186
if len(to_remain) > 0:
187
f = open(patch_path, 'w')
188
for patch in to_remain:
192
def shelve(self, patch_source, all=False, message=None):
193
self._check_upgrade()
195
patches = patch_source.readpatches()
200
to_shelve = ShelveHunkSelector(patches).select()[0]
202
if len(to_shelve) == 0:
203
raise CommandError('Nothing to shelve')
206
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
207
message = "Changes shelved on %s" % timestamp
209
patch_path = self.next_patch()
210
self.log('Shelving to %s/%s: "%s"\n' % \
211
(self.name, os.path.basename(patch_path), message))
213
f = open(patch_path, 'a')
215
assert '\n' not in message
216
f.write("%s%s\n" % (self.MESSAGE_PREFIX, message))
218
for patch in to_shelve:
226
self._run_patch(to_shelve, reverse=True, dry_run=True)
227
self._run_patch(to_shelve, reverse=True)
230
self._run_patch(to_shelve, reverse=True, strip=1, dry_run=True)
231
self._run_patch(to_shelve, reverse=True, strip=1)
233
raise CommandError("Failed removing shelved changes from the"
236
def _run_patch(self, patches, strip=0, reverse=False, dry_run=False):
237
args = ['patch', '-d', self.base, '-s', '-p%d' % strip, '-f']
239
if sys.platform == "win32":
240
args.append('--binary')
245
args.append('--dry-run')
246
stdout = stderr = subprocess.PIPE
248
stdout = stderr = None
250
process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=stdout,
252
for patch in patches:
253
process.stdin.write(str(patch))
255
process.communicate()
257
result = process.wait()
263
def _check_upgrade(self):
264
if len(self._list_old_shelves()) > 0:
265
raise CommandError("Old format shelves found, either upgrade " \
268
def _list_old_shelves(self):
270
stem = os.path.join(self.base, '.bzr-shelf')
272
patches = glob.glob(stem)
273
patches.extend(glob.glob(stem + '-*[!~]'))
275
if len(patches) == 0:
278
def patch_index(name):
281
return int(name[len(stem) + 1:])
283
# patches might not be sorted in the right order
285
for patch in patches:
289
patch_ids.append(int(patch[len(stem) + 1:]))
298
patches.append('%s-%s' % (stem, id))
303
patches = self._list_old_shelves()
305
if len(patches) == 0:
306
self.log('No old-style shelves found to upgrade.\n')
309
for patch in patches:
310
old_file = open(patch, 'r')
311
new_path = self.next_patch()
312
new_file = open(new_path, 'w')
313
new_file.write(old_file.read())
316
self.log('Copied %s to %s/%s\n' % (os.path.basename(patch),
317
self.name, os.path.basename(new_path)))
318
rename(patch, patch + '~')