1
# Copyright (C) 2008 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
from cStringIO import StringIO
38
class ShelfReporter(object):
41
self.delta_reporter = delta._ChangeReporter()
44
trace.warning('No changes to shelve.')
46
def shelved_id(self, shelf_id):
47
trace.note('Changes shelved with id "%d".' % shelf_id)
49
def selected_changes(self, transform):
50
trace.note("Selected changes:")
51
changes = transform.iter_changes()
52
delta.report_changes(changes, self.delta_reporter)
55
class Shelver(object):
56
"""Interactively shelve the changes in a working tree."""
58
def __init__(self, work_tree, target_tree, diff_writer=None, auto=False,
59
auto_apply=False, file_list=None, message=None,
60
destroy=False, manager=None, reporter=None):
63
:param work_tree: The working tree to shelve changes from.
64
:param target_tree: The "unchanged" / old tree to compare the
66
:param auto: If True, shelve each possible change.
67
:param auto_apply: If True, shelve changes with no final prompt.
68
:param file_list: If supplied, only files in this list may be shelved.
69
:param message: The message to associate with the shelved changes.
70
:param destroy: Change the working tree without storing the shelved
72
:param manager: The shelf manager to use.
74
self.work_tree = work_tree
75
self.target_tree = target_tree
76
self.diff_writer = diff_writer
77
if self.diff_writer is None:
78
self.diff_writer = sys.stdout
80
manager = work_tree.get_shelf_manager()
81
self.manager = manager
83
self.auto_apply = auto_apply
84
self.file_list = file_list
85
self.message = message
86
self.destroy = destroy
88
reporter = ShelfReporter()
89
self.reporter = reporter
92
def from_args(klass, diff_writer, revision=None, all=False, file_list=None,
93
message=None, directory='.', destroy=False):
94
"""Create a shelver from commandline arguments.
96
:param revision: RevisionSpec of the revision to compare to.
97
:param all: If True, shelve all changes without prompting.
98
:param file_list: If supplied, only files in this list may be shelved.
99
:param message: The message to associate with the shelved changes.
100
:param directory: The directory containing the working tree.
101
:param destroy: Change the working tree without storing the shelved
104
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,
112
"""Interactively shelve the changes."""
113
creator = shelf.ShelfCreator(self.work_tree, self.target_tree,
115
self.tempdir = tempfile.mkdtemp()
118
for change in creator.iter_shelvable():
119
if change[0] == 'modify text':
121
changes_shelved += self.handle_modify_text(creator,
123
except errors.BinaryFile:
124
if self.prompt_bool('Shelve binary changes?'):
126
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])
152
if changes_shelved > 0:
153
self.reporter.selected_changes(creator.work_transform)
154
if (self.auto_apply or self.prompt_bool(
155
'Shelve %d change(s)?' % changes_shelved)):
158
trace.note('Selected changes destroyed.')
160
shelf_id = self.manager.shelve_changes(creator,
162
self.reporter.shelved_id(shelf_id)
164
self.reporter.no_changes()
166
shutil.rmtree(self.tempdir)
169
def get_parsed_patch(self, file_id):
170
"""Return a parsed version of a file's patch.
172
:param file_id: The id of the file to generate a patch for.
173
:return: A patches.Patch.
175
old_path = self.target_tree.id2path(file_id)
176
new_path = self.work_tree.id2path(file_id)
177
diff_file = StringIO()
178
text_differ = diff.DiffText(self.target_tree, self.work_tree,
180
patch = text_differ.diff(file_id, old_path, new_path, 'file', 'file')
182
return patches.parse_patch(diff_file)
184
def prompt(self, message):
185
"""Prompt the user for a character.
187
:param message: The message to prompt a user with.
188
:return: A character.
190
sys.stdout.write(message)
191
char = osutils.getchar()
192
sys.stdout.write("\r" + ' ' * len(message) + '\r')
196
def prompt_bool(self, question, long=False):
197
"""Prompt the user with a yes/no question.
199
This may be overridden by self.auto. It may also *set* self.auto. It
200
may also raise UserAbort.
201
:param question: The question to ask the user.
202
:return: True or False
207
prompt = ' [(y)es, (N)o, (f)inish, or (q)uit]'
210
char = self.prompt(question + prompt)
217
return self.prompt_bool(question, long=True)
219
raise errors.UserAbort()
223
def handle_modify_text(self, creator, file_id):
224
"""Provide diff hunk selection for modified text.
226
:param creator: a ShelfCreator
227
:param file_id: The id of the file to shelve.
228
: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))
232
textfile.check_text_lines(target_lines)
233
parsed = self.get_parsed_patch(file_id)
237
self.diff_writer.write(parsed.get_header())
238
for hunk in parsed.hunks:
239
self.diff_writer.write(str(hunk))
240
if not self.prompt_bool('Shelve?'):
241
hunk.mod_pos += offset
242
final_hunks.append(hunk)
244
offset -= (hunk.mod_range - hunk.orig_range)
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)
253
class Unshelver(object):
254
"""Unshelve changes into a working tree."""
257
def from_args(klass, shelf_id=None, action='apply', directory='.'):
258
"""Create an unshelver from commandline arguments.
260
:param shelf_id: Integer id of the shelf, as a string.
261
:param action: action to perform. May be 'apply', 'dry-run',
263
:param directory: The directory to unshelve changes into.
265
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
286
return klass(tree, manager, shelf_id, apply_changes, delete_shelf,
289
def __init__(self, tree, manager, shelf_id, apply_changes=True,
290
delete_shelf=True, read_shelf=True):
293
:param tree: The working tree to unshelve into.
294
:param manager: The ShelveManager containing the shelved changes.
296
:param apply_changes: If True, apply the shelved changes to the
298
:param delete_shelf: If True, delete the changes from the shelf.
299
:param read_shelf: If True, read the changes from the shelf.
302
manager = tree.get_shelf_manager()
303
self.manager = manager
304
self.shelf_id = shelf_id
305
self.apply_changes = apply_changes
306
self.delete_shelf = delete_shelf
307
self.read_shelf = read_shelf
310
"""Perform the unshelving operation."""
311
self.tree.lock_write()
312
cleanups = [self.tree.unlock]
315
unshelver = self.manager.get_unshelver(self.shelf_id)
316
cleanups.append(unshelver.finalize)
317
if unshelver.message is not None:
318
trace.note('Message: %s' % unshelver.message)
319
change_reporter = delta._ChangeReporter()
320
task = ui.ui_factory.nested_progress_bar()
322
merger = unshelver.make_merger(task)
323
merger.change_reporter = change_reporter
324
if self.apply_changes:
327
self.show_changes(merger)
330
if self.delete_shelf:
331
self.manager.delete_shelf(self.shelf_id)
333
for cleanup in reversed(cleanups):
336
def show_changes(self, merger):
337
"""Show the changes that this operation specifies."""
338
tree_merger = merger.make_merger()
339
# This implicitly shows the changes via the reporter, so we're done...
340
tt = tree_merger.make_preview_transform()