3
from patches import parse_patches
4
from datetime import datetime
5
from errors import CommandError, PatchFailed, PatchInvokeError
6
from hunk_selector import ShelveHunkSelector, UnshelveHunkSelector
7
from patch import run_patch
8
from patchsource import PatchSource, FilePatchSource
9
from bzrlib.osutils import rename
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
15
DEFAULT_IGNORE.append('./.bzr-shelf*')
17
class QuitException(Exception):
11
20
class Shelf(object):
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
rename(path, '%s~' % path)
61
def display(self, patch=None):
63
path = self.last_patch()
65
raise CommandError("No patches on shelf.")
67
path = self.__path_from_user(patch)
68
sys.stdout.write(open(path).read())
71
indexes = self.__list()
72
self.log("Patches on shelf '%s':" % self.name)
78
msg = self.get_patch_message(self.__path(index))
80
msg = "No message saved with patch."
81
self.log(' %.2d: %s\n' % (index, msg))
83
def __path_from_user(self, patch_id):
85
patch_index = int(patch_id)
86
except (TypeError, ValueError):
87
raise CommandError("Invalid patch name '%s'" % patch_id)
89
path = self.__path(patch_index)
91
if not os.path.exists(path):
92
raise CommandError("Patch '%s' doesn't exist on shelf %s!" % \
93
(patch_id, self.name))
97
def __path(self, index):
98
return os.path.join(self.dir, '%.2d' % index)
100
def next_patch(self):
101
indexes = self.__list()
103
if len(indexes) == 0:
106
next = indexes[-1] + 1
107
return self.__path(next)
110
patches = os.listdir(self.dir)
114
continue # ignore backup files
116
indexes.append(int(f))
118
self.log("Warning: Ignoring junk file '%s' on shelf.\n" % f)
123
def last_patch(self):
124
indexes = self.__list()
126
if len(indexes) == 0:
129
return self.__path(indexes[-1])
131
def get_patch_message(self, patch_path):
132
patch = open(patch_path, 'r').read()
134
if not patch.startswith(self.MESSAGE_PREFIX):
136
return patch[len(self.MESSAGE_PREFIX):patch.index('\n')]
138
def unshelve(self, patch_source, patch_name=None, all=False, force=False,
140
self._check_upgrade()
142
if no_color is False:
146
if patch_name is None:
147
patch_path = self.last_patch()
149
patch_path = self.__path_from_user(patch_name)
151
if patch_path is None:
152
raise CommandError("No patch found on shelf %s" % self.name)
154
patches = FilePatchSource(patch_path).readpatches()
156
to_unshelve = patches
159
hs = UnshelveHunkSelector(patches, color)
160
to_unshelve, to_remain = hs.select()
162
if len(to_unshelve) == 0:
163
raise CommandError('Nothing to unshelve')
165
message = self.get_patch_message(patch_path)
167
message = "No message saved with patch."
168
self.log('Unshelving from %s/%s: "%s"\n' % \
169
(self.name, os.path.basename(patch_path), message))
172
self._run_patch(to_unshelve, dry_run=True)
173
self._run_patch(to_unshelve)
176
self._run_patch(to_unshelve, strip=1, dry_run=True)
177
self._run_patch(to_unshelve, strip=1)
180
self.log('Warning: Unshelving failed, forcing as ' \
181
'requested. Shelf will not be modified.\n')
183
self._run_patch(to_unshelve)
187
raise CommandError("Your shelved patch no " \
188
"longer applies cleanly to the working tree!")
190
# Backup the shelved patch
191
rename(patch_path, '%s~' % patch_path)
193
if len(to_remain) > 0:
194
f = open(patch_path, 'w')
195
for patch in to_remain:
199
def shelve(self, patch_source, all=False, message=None, no_color=False):
200
self._check_upgrade()
201
if no_color is False:
206
patches = patch_source.readpatches()
211
to_shelve = ShelveHunkSelector(patches, color).select()[0]
213
if len(to_shelve) == 0:
214
raise CommandError('Nothing to shelve')
217
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
218
message = "Changes shelved on %s" % timestamp
220
patch_path = self.next_patch()
221
self.log('Shelving to %s/%s: "%s"\n' % \
222
(self.name, os.path.basename(patch_path), message))
224
f = open(patch_path, 'a')
226
assert '\n' not in message
227
f.write("%s%s\n" % (self.MESSAGE_PREFIX, message))
229
for patch in to_shelve:
237
self._run_patch(to_shelve, reverse=True, dry_run=True)
238
self._run_patch(to_shelve, reverse=True)
241
self._run_patch(to_shelve, reverse=True, strip=1, dry_run=True)
242
self._run_patch(to_shelve, reverse=True, strip=1)
244
raise CommandError("Failed removing shelved changes from the"
247
def _run_patch(self, patches, strip=0, reverse=False, dry_run=False):
248
run_patch(self.base, patches, strip, reverse, dry_run)
250
def _check_upgrade(self):
251
if len(self._list_old_shelves()) > 0:
252
raise CommandError("Old format shelves found, either upgrade " \
255
def _list_old_shelves(self):
257
stem = os.path.join(self.base, '.bzr-shelf')
259
patches = glob.glob(stem)
260
patches.extend(glob.glob(stem + '-*[!~]'))
262
if len(patches) == 0:
265
def patch_index(name):
21
def __init__(self, location):
22
self.branch = Branch.open_containing(location)[0]
24
def shelf_suffix(self, index):
34
yield self.shelf_suffix(i)
37
stem = os.path.join(self.branch.base, '.bzr-shelf')
38
for end in name_sequence():
40
if not os.path.exists(name):
44
stem = os.path.join(self.branch.base, '.bzr-shelf')
45
shelves = glob.glob(stem)
46
shelves.extend(glob.glob(stem + '-*'))
47
def shelf_index(name):
268
return int(name[len(stem) + 1:])
270
# patches might not be sorted in the right order
272
for patch in patches:
276
patch_ids.append(int(patch[len(stem) + 1:]))
285
patches.append('%s-%s' % (stem, id))
290
patches = self._list_old_shelves()
50
return int(name[len(stem)+1:])
51
shelvenums = [shelf_index(f) for f in shelves]
54
if len(shelvenums) == 0:
56
return stem + self.shelf_suffix(shelvenums[-1])
58
def get_shelf_message(self, shelf):
60
if not shelf.startswith(prefix):
62
return shelf[len(prefix):shelf.index('\n')]
65
shelf = self.last_shelf()
68
raise Exception("No shelf found in '%s'" % self.branch.base)
70
patch = open(shelf, 'r').read()
72
print >>sys.stderr, "Reapplying shelved patches",
73
message = self.get_shelf_message(patch)
74
if message is not None:
75
print >>sys.stderr, ' "%s"' % message
77
print >>sys.stderr, ""
78
pipe = os.popen('patch -d %s -s -p0' % self.branch.base, 'w')
82
if pipe.close() is not None:
83
raise Exception("Failed running patch!")
87
diff_stat = DiffStat(self.get_patches(None, None))
88
print 'Diff status is now:\n', diff_stat
92
def get_patches(self, revision, file_list):
93
from StringIO import StringIO
94
from bzrlib.diff import show_diff
96
show_diff(self.branch, revision, specific_files=file_list, output=out)
98
return out.readlines()
100
def shelve(self, all_hunks=False, message=None, revision=None,
102
patches = parse_patches(self.get_patches(revision, file_list))
106
patches = HunkSelector(patches).select()
107
except QuitException:
292
110
if len(patches) == 0:
293
self.log('No old-style shelves found to upgrade.\n')
296
for patch in patches:
297
old_file = open(patch, 'r')
298
new_path = self.next_patch()
299
new_file = open(new_path, 'w')
300
new_file.write(old_file.read())
303
self.log('Copied %s to %s/%s\n' % (os.path.basename(patch),
304
self.name, os.path.basename(new_path)))
305
rename(patch, patch + '~')
111
print >>sys.stderr, 'Nothing to shelve'
114
shelf = self.next_shelf()
115
print >>sys.stderr, "Saving shelved patches to", shelf
116
shelf = open(shelf, 'a')
117
if message is not None:
118
assert '\n' not in message
119
shelf.write("# shelf: %s\n" % message)
120
for patch in patches:
121
shelf.write(str(patch))
124
os.fsync(shelf.fileno())
127
print >>sys.stderr, "Reverting shelved patches"
128
pipe = os.popen('patch -d %s -sR -p0' % self.branch.base, 'w')
129
for patch in patches:
130
pipe.write(str(patch))
133
if pipe.close() is not None:
134
raise Exception("Failed running patch!")
136
diff_stat = DiffStat(self.get_patches(None, None))
137
print 'Diff status is now:\n', diff_stat