40
class UseEditor(Exception):
41
"""Use an editor instead of selecting hunks."""
38
44
class ShelfReporter(object):
46
vocab = {'add file': 'Shelve adding file "%(path)s"?',
47
'binary': 'Shelve binary changes?',
48
'change kind': 'Shelve changing "%s" from %(other)s'
50
'delete file': 'Shelve removing file "%(path)s"?',
51
'final': 'Shelve %d change(s)?',
53
'modify target': 'Shelve changing target of'
54
' "%(path)s" from "%(other)s" to "%(this)s"?',
55
'rename': 'Shelve renaming "%(other)s" =>'
40
61
def __init__(self):
41
62
self.delta_reporter = delta._ChangeReporter()
43
64
def no_changes(self):
65
"""Report that no changes were selected to apply."""
44
66
trace.warning('No changes to shelve.')
46
68
def shelved_id(self, shelf_id):
69
"""Report the id changes were shelved to."""
47
70
trace.note('Changes shelved with id "%d".' % shelf_id)
72
def changes_destroyed(self):
73
"""Report that changes were made without shelving."""
74
trace.note('Selected changes destroyed.')
49
76
def selected_changes(self, transform):
77
"""Report the changes that were selected."""
50
78
trace.note("Selected changes:")
51
79
changes = transform.iter_changes()
52
80
delta.report_changes(changes, self.delta_reporter)
82
def prompt_change(self, change):
83
"""Determine the prompt for a change to apply."""
84
if change[0] == 'rename':
85
vals = {'this': change[3], 'other': change[2]}
86
elif change[0] == 'change kind':
87
vals = {'path': change[4], 'other': change[2], 'this': change[3]}
88
elif change[0] == 'modify target':
89
vals = {'path': change[2], 'other': change[3], 'this': change[4]}
91
vals = {'path': change[3]}
92
prompt = self.vocab[change[0]] % vals
96
class ApplyReporter(ShelfReporter):
98
vocab = {'add file': 'Delete file "%(path)s"?',
99
'binary': 'Apply binary changes?',
100
'change kind': 'Change "%(path)s" from %(this)s'
102
'delete file': 'Add file "%(path)s"?',
103
'final': 'Apply %d change(s)?',
104
'hunk': 'Apply change?',
105
'modify target': 'Change target of'
106
' "%(path)s" from "%(this)s" to "%(other)s"?',
107
'rename': 'Rename "%(this)s" => "%(other)s"?',
112
def changes_destroyed(self):
55
116
class Shelver(object):
56
117
"""Interactively shelve the changes in a working tree."""
87
149
if reporter is None:
88
150
reporter = ShelfReporter()
89
151
self.reporter = reporter
152
config = self.work_tree.branch.get_config()
153
self.change_editor = config.get_change_editor(target_tree, work_tree)
154
self.work_tree.lock_tree_write()
92
157
def from_args(klass, diff_writer, revision=None, all=False, file_list=None,
93
158
message=None, directory='.', destroy=False):
94
159
"""Create a shelver from commandline arguments.
161
The returned shelver wil have a work_tree that is locked and should
96
164
:param revision: RevisionSpec of the revision to compare to.
97
165
:param all: If True, shelve all changes without prompting.
98
166
:param file_list: If supplied, only files in this list may be shelved.
104
172
tree, path = workingtree.WorkingTree.open_containing(directory)
105
target_tree = builtins._get_one_revision_tree('shelf2', revision,
107
files = builtins.safe_relpath_files(tree, file_list)
108
return klass(tree, target_tree, diff_writer, all, all, files, message,
173
# Ensure that tree is locked for the lifetime of target_tree, as
174
# target tree may be reading from the same dirstate.
175
tree.lock_tree_write()
177
target_tree = builtins._get_one_revision_tree('shelf2', revision,
179
files = builtins.safe_relpath_files(tree, file_list)
180
return klass(tree, target_tree, diff_writer, all, all, files,
112
186
"""Interactively shelve the changes."""
121
195
changes_shelved += self.handle_modify_text(creator,
123
197
except errors.BinaryFile:
124
if self.prompt_bool('Shelve binary changes?'):
198
if self.prompt_bool(self.reporter.vocab['binary']):
125
199
changes_shelved += 1
126
200
creator.shelve_content_change(change[1])
127
if change[0] == 'add file':
128
if self.prompt_bool('Shelve adding file "%s"?'
130
creator.shelve_creation(change[1])
132
if change[0] == 'delete file':
133
if self.prompt_bool('Shelve removing file "%s"?'
135
creator.shelve_deletion(change[1])
137
if change[0] == 'change kind':
138
if self.prompt_bool('Shelve changing "%s" from %s to %s? '
139
% (change[4], change[2], change[3])):
140
creator.shelve_content_change(change[1])
142
if change[0] == 'rename':
143
if self.prompt_bool('Shelve renaming "%s" => "%s"?' %
145
creator.shelve_rename(change[1])
147
if change[0] == 'modify target':
148
if self.prompt_bool('Shelve changing target of "%s" '
149
'from "%s" to "%s"?' % change[2:]):
150
creator.shelve_modify_target(change[1])
202
if self.prompt_bool(self.reporter.prompt_change(change)):
203
creator.shelve_change(change)
151
204
changes_shelved += 1
152
205
if changes_shelved > 0:
153
206
self.reporter.selected_changes(creator.work_transform)
154
207
if (self.auto_apply or self.prompt_bool(
155
'Shelve %d change(s)?' % changes_shelved)):
208
self.reporter.vocab['final'] % changes_shelved)):
157
210
creator.transform()
158
trace.note('Selected changes destroyed.')
211
self.reporter.changes_destroyed()
160
213
shelf_id = self.manager.shelve_changes(creator,
166
219
shutil.rmtree(self.tempdir)
167
220
creator.finalize()
169
def get_parsed_patch(self, file_id):
223
if self.change_editor is not None:
224
self.change_editor.finish()
225
self.work_tree.unlock()
228
def get_parsed_patch(self, file_id, invert=False):
170
229
"""Return a parsed version of a file's patch.
172
231
:param file_id: The id of the file to generate a patch for.
232
:param invert: If True, provide an inverted patch (insertions displayed
233
as removals, removals displayed as insertions).
173
234
:return: A patches.Patch.
175
old_path = self.target_tree.id2path(file_id)
176
new_path = self.work_tree.id2path(file_id)
177
236
diff_file = StringIO()
178
text_differ = diff.DiffText(self.target_tree, self.work_tree,
238
old_tree = self.work_tree
239
new_tree = self.target_tree
241
old_tree = self.target_tree
242
new_tree = self.work_tree
243
old_path = old_tree.id2path(file_id)
244
new_path = new_tree.id2path(file_id)
245
text_differ = diff.DiffText(old_tree, new_tree, diff_file)
180
246
patch = text_differ.diff(file_id, old_path, new_path, 'file', 'file')
181
247
diff_file.seek(0)
182
248
return patches.parse_patch(diff_file)
187
253
:param message: The message to prompt a user with.
188
254
:return: A character.
256
if not sys.stdin.isatty():
257
# Since there is no controlling terminal we will hang when trying
258
# to prompt the user, better abort now. See
259
# https://code.launchpad.net/~bialix/bzr/shelve-no-tty/+merge/14905
261
raise errors.BzrError("You need a controlling terminal.")
190
262
sys.stdout.write(message)
191
263
char = osutils.getchar()
192
264
sys.stdout.write("\r" + ' ' * len(message) + '\r')
193
265
sys.stdout.flush()
196
def prompt_bool(self, question, long=False):
268
def prompt_bool(self, question, long=False, allow_editor=False):
197
269
"""Prompt the user with a yes/no question.
199
271
This may be overridden by self.auto. It may also *set* self.auto. It
223
302
def handle_modify_text(self, creator, file_id):
303
"""Handle modified text, by using hunk selection or file editing.
305
:param creator: A ShelfCreator.
306
:param file_id: The id of the file that was modified.
307
:return: The number of changes.
309
work_tree_lines = self.work_tree.get_file_lines(file_id)
311
lines, change_count = self._select_hunks(creator, file_id,
314
lines, change_count = self._edit_file(file_id, work_tree_lines)
315
if change_count != 0:
316
creator.shelve_lines(file_id, lines)
319
def _select_hunks(self, creator, file_id, work_tree_lines):
224
320
"""Provide diff hunk selection for modified text.
322
If self.reporter.invert_diff is True, the diff is inverted so that
323
insertions are displayed as removals and vice versa.
226
325
:param creator: a ShelfCreator
227
326
:param file_id: The id of the file to shelve.
327
:param work_tree_lines: Line contents of the file in the working tree.
228
328
:return: number of shelved hunks.
230
target_lines = self.target_tree.get_file_lines(file_id)
231
textfile.check_text_lines(self.work_tree.get_file_lines(file_id))
330
if self.reporter.invert_diff:
331
target_lines = work_tree_lines
333
target_lines = self.target_tree.get_file_lines(file_id)
334
textfile.check_text_lines(work_tree_lines)
232
335
textfile.check_text_lines(target_lines)
233
parsed = self.get_parsed_patch(file_id)
336
parsed = self.get_parsed_patch(file_id, self.reporter.invert_diff)
235
338
if not self.auto:
237
340
self.diff_writer.write(parsed.get_header())
238
341
for hunk in parsed.hunks:
239
342
self.diff_writer.write(str(hunk))
240
if not self.prompt_bool('Shelve?'):
343
selected = self.prompt_bool(self.reporter.vocab['hunk'],
344
allow_editor=(self.change_editor
346
if not self.reporter.invert_diff:
347
selected = (not selected)
241
349
hunk.mod_pos += offset
242
350
final_hunks.append(hunk)
244
352
offset -= (hunk.mod_range - hunk.orig_range)
245
353
sys.stdout.flush()
246
if len(parsed.hunks) == len(final_hunks):
248
patched = patches.iter_patched_from_hunks(target_lines, final_hunks)
249
creator.shelve_lines(file_id, list(patched))
250
return len(parsed.hunks) - len(final_hunks)
354
if self.reporter.invert_diff:
355
change_count = len(final_hunks)
357
change_count = len(parsed.hunks) - len(final_hunks)
358
patched = patches.iter_patched_from_hunks(target_lines,
360
lines = list(patched)
361
return lines, change_count
363
def _edit_file(self, file_id, work_tree_lines):
365
:param file_id: id of the file to edit.
366
:param work_tree_lines: Line contents of the file in the working tree.
367
:return: (lines, change_region_count), where lines is the new line
368
content of the file, and change_region_count is the number of
371
lines = osutils.split_lines(self.change_editor.edit_file(file_id))
372
return lines, self._count_changed_regions(work_tree_lines, lines)
375
def _count_changed_regions(old_lines, new_lines):
376
matcher = patiencediff.PatienceSequenceMatcher(None, old_lines,
378
blocks = matcher.get_matching_blocks()
379
return len(blocks) - 2
253
382
class Unshelver(object):
257
386
def from_args(klass, shelf_id=None, action='apply', directory='.'):
258
387
"""Create an unshelver from commandline arguments.
389
The returned shelver wil have a tree that is locked and should
260
392
:param shelf_id: Integer id of the shelf, as a string.
261
393
:param action: action to perform. May be 'apply', 'dry-run',
263
395
:param directory: The directory to unshelve changes into.
265
397
tree, path = workingtree.WorkingTree.open_containing(directory)
266
manager = tree.get_shelf_manager()
267
if shelf_id is not None:
269
shelf_id = int(shelf_id)
271
raise errors.InvalidShelfId(shelf_id)
273
shelf_id = manager.last_shelf()
275
raise errors.BzrCommandError('No changes are shelved.')
276
trace.note('Unshelving changes with id "%d".' % shelf_id)
280
if action == 'dry-run':
281
apply_changes = False
283
if action == 'delete-only':
284
apply_changes = False
398
tree.lock_tree_write()
400
manager = tree.get_shelf_manager()
401
if shelf_id is not None:
403
shelf_id = int(shelf_id)
405
raise errors.InvalidShelfId(shelf_id)
407
shelf_id = manager.last_shelf()
409
raise errors.BzrCommandError('No changes are shelved.')
410
trace.note('Unshelving changes with id "%d".' % shelf_id)
414
if action == 'dry-run':
415
apply_changes = False
417
if action == 'delete-only':
418
apply_changes = False
286
423
return klass(tree, manager, shelf_id, apply_changes, delete_shelf,