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):
6
from datetime import datetime
7
from errors import CommandError, PatchFailed
8
from hunk_selector import ShelveHunkSelector, UnshelveHunkSelector
9
from patchsource import PatchSource, FilePatchSource
21
11
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):
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)
61
def display(self, patch):
62
path = self.__path_from_user(patch)
63
sys.stdout.write(open(path).read())
66
indexes = self.__list()
67
self.log("Patches on shelf '%s':" % self.name)
73
msg = self.get_patch_message(self.__path(index))
75
msg = "No message saved with patch."
76
self.log(' %.2d: %s\n' % (index, msg))
78
def __path_from_user(self, patch_id):
80
patch_index = int(patch_id)
82
raise CommandError("Invalid patch name '%s'" % patch_id)
84
path = self.__path(patch_index)
86
if not os.path.exists(path):
87
raise CommandError("Patch '%s' doesn't exist on shelf %s!" % \
88
(patch_id, self.name))
92
def __path(self, index):
93
return os.path.join(self.dir, '%.2d' % index)
96
indexes = self.__list()
101
next = indexes[-1] + 1
102
return self.__path(next)
105
patches = os.listdir(self.dir)
109
continue # ignore backup files
111
indexes.append(int(f))
113
self.log("Warning: Ignoring junk file '%s' on shelf.\n" % f)
118
def last_patch(self):
119
indexes = self.__list()
121
if len(indexes) == 0:
124
return self.__path(indexes[-1])
126
def get_patch_message(self, patch_path):
127
patch = open(patch_path, 'r').read()
129
if not patch.startswith(self.MESSAGE_PREFIX):
131
return patch[len(self.MESSAGE_PREFIX):patch.index('\n')]
133
def unshelve(self, patch_source, all_hunks=False, force=False):
134
self._check_upgrade()
136
patch_name = self.last_patch()
138
if patch_name is None:
139
raise CommandError("No patch found on shelf %s" % self.name)
141
hunks = FilePatchSource(patch_name).readhunks()
146
to_unshelve, to_remain = UnshelveHunkSelector(hunks).select()
148
if len(to_unshelve) == 0:
149
raise CommandError('Nothing to unshelve')
151
message = self.get_patch_message(patch_name)
153
message = "No message saved with patch."
154
self.log('Unshelving from %s/%s: "%s"\n' % \
155
(self.name, os.path.basename(patch_name), message))
158
self._run_patch(to_unshelve, dry_run=True)
159
self._run_patch(to_unshelve)
162
self._run_patch(to_unshelve, strip=0, dry_run=True)
163
self._run_patch(to_unshelve, strip=0)
166
self.log('Warning: Unshelving failed, forcing as ' \
167
'requested. Shelf will not be modified.\n')
169
self._run_patch(to_unshelve)
173
raise CommandError("Your shelved patch no " \
174
"longer applies cleanly to the working tree!")
176
# Backup the shelved patch
177
os.rename(patch_name, '%s~' % patch_name)
179
if len(to_remain) > 0:
180
f = open(patch_name, 'w')
181
for hunk in to_remain:
185
def shelve(self, patch_source, all_hunks=False, message=None):
186
self._check_upgrade()
188
hunks = patch_source.readhunks()
193
to_shelve = ShelveHunkSelector(hunks).select()[0]
195
if len(to_shelve) == 0:
196
raise CommandError('Nothing to shelve')
199
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
200
message = "Changes shelved on %s" % timestamp
202
patch_name = self.next_patch()
203
self.log('Shelving to %s/%s: "%s"\n' % \
204
(self.name, os.path.basename(patch_name), message))
206
patch = open(patch_name, 'a')
208
assert '\n' not in message
209
patch.write("%s%s\n" % (self.MESSAGE_PREFIX, message))
211
for hunk in to_shelve:
212
patch.write(str(hunk))
215
os.fsync(patch.fileno())
219
self._run_patch(to_shelve, reverse=True, dry_run=True)
220
self._run_patch(to_shelve, reverse=True)
223
self._run_patch(to_shelve, reverse=True, strip=0, dry_run=True)
224
self._run_patch(to_shelve, reverse=True, strip=0)
226
raise CommandError("Failed removing shelved changes from the"
229
def _run_patch(self, patches, strip=1, reverse=False, dry_run=False):
230
args = ['patch', '-d', self.base, '-s', '-p%d' % strip, '-f']
234
args.append('--dry-run')
235
stdout = stderr = subprocess.PIPE
237
stdout = stderr = None
239
process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=stdout,
241
for patch in patches:
242
process.stdin.write(str(patch))
244
process.communicate()
246
result = process.wait()
252
def _check_upgrade(self):
253
if len(self._list_old_shelves()) > 0:
254
raise CommandError("Old format shelves found, either upgrade " \
257
def _list_old_shelves(self):
259
stem = os.path.join(self.base, '.bzr-shelf')
261
patches = glob.glob(stem)
262
patches.extend(glob.glob(stem + '-*[!~]'))
264
if len(patches) == 0:
267
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:
270
return int(name[len(stem) + 1:])
272
# patches might not be sorted in the right order
274
for patch in patches:
278
patch_ids.append(int(patch[len(stem) + 1:]))
287
patches.append('%s-%s' % (stem, id))
292
patches = self._list_old_shelves()
105
294
if len(patches) == 0:
106
print >>sys.stderr, 'Nothing to shelve'
295
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
298
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', '-p1', '-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")
299
old_file = open(patch, 'r')
300
new_path = self.next_patch()
301
new_file = open(new_path, 'w')
302
new_file.write(old_file.read())
305
self.log('Copied %s to %s/%s\n' % (os.path.basename(patch),
306
self.name, os.path.basename(new_path)))
307
os.rename(patch, patch + '~')