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 Shelver(object):
39
"""Interactively shelve the changes in a working tree."""
41
def __init__(self, work_tree, target_tree, diff_writer=None, auto=False,
42
auto_apply=False, file_list=None, message=None,
46
:param work_tree: The working tree to shelve changes from.
47
:param target_tree: The "unchanged" / old tree to compare the
49
:param auto: If True, shelve each possible change.
50
:param auto_apply: If True, shelve changes with no final prompt.
51
:param file_list: If supplied, only files in this list may be shelved.
52
:param message: The message to associate with the shelved changes.
53
:param destroy: Change the working tree without storing the shelved
56
self.work_tree = work_tree
57
self.target_tree = target_tree
58
self.diff_writer = diff_writer
59
if self.diff_writer is None:
60
self.diff_writer = sys.stdout
61
self.manager = work_tree.get_shelf_manager()
63
self.auto_apply = auto_apply
64
self.file_list = file_list
65
self.message = message
66
self.destroy = destroy
69
def from_args(klass, diff_writer, revision=None, all=False, file_list=None,
70
message=None, directory='.', destroy=False):
71
"""Create a shelver from commandline arguments.
73
:param revision: RevisionSpec of the revision to compare to.
74
:param all: If True, shelve all changes without prompting.
75
:param file_list: If supplied, only files in this list may be shelved.
76
:param message: The message to associate with the shelved changes.
77
:param directory: The directory containing the working tree.
78
:param destroy: Change the working tree without storing the shelved
81
tree, path = workingtree.WorkingTree.open_containing(directory)
82
target_tree = builtins._get_one_revision_tree('shelf2', revision,
84
files = builtins.safe_relpath_files(tree, file_list)
85
return klass(tree, target_tree, diff_writer, all, all, files, message,
89
"""Interactively shelve the changes."""
90
creator = shelf.ShelfCreator(self.work_tree, self.target_tree,
92
self.tempdir = tempfile.mkdtemp()
95
for change in creator.iter_shelvable():
96
if change[0] == 'modify text':
98
changes_shelved += self.handle_modify_text(creator,
100
except errors.BinaryFile:
101
if self.prompt_bool('Shelve binary changes?'):
103
creator.shelve_content_change(change[1])
104
if change[0] == 'add file':
105
if self.prompt_bool('Shelve adding file "%s"?'
107
creator.shelve_creation(change[1])
109
if change[0] == 'delete file':
110
if self.prompt_bool('Shelve removing file "%s"?'
112
creator.shelve_deletion(change[1])
114
if change[0] == 'change kind':
115
if self.prompt_bool('Shelve changing "%s" from %s to %s? '
116
% (change[4], change[2], change[3])):
117
creator.shelve_content_change(change[1])
119
if change[0] == 'rename':
120
if self.prompt_bool('Shelve renaming "%s" => "%s"?' %
122
creator.shelve_rename(change[1])
124
if change[0] == 'modify target':
125
if self.prompt_bool('Shelve changing target of "%s" '
126
'from "%s" to "%s"?' % change[2:]):
127
creator.shelve_modify_target(change[1])
129
if changes_shelved > 0:
130
trace.note("Selected changes:")
131
changes = creator.work_transform.iter_changes()
132
reporter = delta._ChangeReporter()
133
delta.report_changes(changes, reporter)
134
if (self.auto_apply or self.prompt_bool(
135
'Shelve %d change(s)?' % changes_shelved)):
138
trace.note('Selected changes destroyed.')
140
shelf_id = self.manager.shelve_changes(creator,
142
trace.note('Changes shelved with id "%d".' % shelf_id)
144
trace.warning('No changes to shelve.')
146
shutil.rmtree(self.tempdir)
149
def get_parsed_patch(self, file_id):
150
"""Return a parsed version of a file's patch.
152
:param file_id: The id of the file to generate a patch for.
153
:return: A patches.Patch.
155
old_path = self.target_tree.id2path(file_id)
156
new_path = self.work_tree.id2path(file_id)
157
diff_file = StringIO()
158
text_differ = diff.DiffText(self.target_tree, self.work_tree,
160
patch = text_differ.diff(file_id, old_path, new_path, 'file', 'file')
162
return patches.parse_patch(diff_file)
164
def prompt(self, message):
165
"""Prompt the user for a character.
167
:param message: The message to prompt a user with.
168
:return: A character.
170
sys.stdout.write(message)
171
char = osutils.getchar()
172
sys.stdout.write("\r" + ' ' * len(message) + '\r')
176
def prompt_bool(self, question, long=False):
177
"""Prompt the user with a yes/no question.
179
This may be overridden by self.auto. It may also *set* self.auto. It
180
may also raise UserAbort.
181
:param question: The question to ask the user.
182
:return: True or False
187
prompt = ' [(y)es, (N)o, (f)inish, or (q)uit]'
190
char = self.prompt(question + prompt)
197
return self.prompt_bool(question, long=True)
199
raise errors.UserAbort()
203
def handle_modify_text(self, creator, file_id):
204
"""Provide diff hunk selection for modified text.
206
:param creator: a ShelfCreator
207
:param file_id: The id of the file to shelve.
208
:return: number of shelved hunks.
210
target_lines = self.target_tree.get_file_lines(file_id)
211
textfile.check_text_lines(self.work_tree.get_file_lines(file_id))
212
textfile.check_text_lines(target_lines)
213
parsed = self.get_parsed_patch(file_id)
217
self.diff_writer.write(parsed.get_header())
218
for hunk in parsed.hunks:
219
self.diff_writer.write(str(hunk))
220
if not self.prompt_bool('Shelve?'):
221
hunk.mod_pos += offset
222
final_hunks.append(hunk)
224
offset -= (hunk.mod_range - hunk.orig_range)
226
if len(parsed.hunks) == len(final_hunks):
228
patched = patches.iter_patched_from_hunks(target_lines, final_hunks)
229
creator.shelve_lines(file_id, list(patched))
230
return len(parsed.hunks) - len(final_hunks)
233
class Unshelver(object):
234
"""Unshelve changes into a working tree."""
237
def from_args(klass, shelf_id=None, action='apply', directory='.'):
238
"""Create an unshelver from commandline arguments.
240
:param shelf_id: Integer id of the shelf, as a string.
241
:param action: action to perform. May be 'apply', 'dry-run',
243
:param directory: The directory to unshelve changes into.
245
tree, path = workingtree.WorkingTree.open_containing(directory)
246
manager = tree.get_shelf_manager()
247
if shelf_id is not None:
249
shelf_id = int(shelf_id)
251
raise errors.InvalidShelfId(shelf_id)
253
shelf_id = manager.last_shelf()
255
raise errors.BzrCommandError('No changes are shelved.')
256
trace.note('Unshelving changes with id "%d".' % shelf_id)
260
if action == 'dry-run':
261
apply_changes = False
263
if action == 'delete-only':
264
apply_changes = False
266
return klass(tree, manager, shelf_id, apply_changes, delete_shelf,
269
def __init__(self, tree, manager, shelf_id, apply_changes=True,
270
delete_shelf=True, read_shelf=True):
273
:param tree: The working tree to unshelve into.
274
:param manager: The ShelveManager containing the shelved changes.
276
:param apply_changes: If True, apply the shelved changes to the
278
:param delete_shelf: If True, delete the changes from the shelf.
279
:param read_shelf: If True, read the changes from the shelf.
282
manager = tree.get_shelf_manager()
283
self.manager = manager
284
self.shelf_id = shelf_id
285
self.apply_changes = apply_changes
286
self.delete_shelf = delete_shelf
287
self.read_shelf = read_shelf
290
"""Perform the unshelving operation."""
291
self.tree.lock_write()
292
cleanups = [self.tree.unlock]
295
unshelver = self.manager.get_unshelver(self.shelf_id)
296
cleanups.append(unshelver.finalize)
297
if unshelver.message is not None:
298
trace.note('Message: %s' % unshelver.message)
299
change_reporter = delta._ChangeReporter()
300
task = ui.ui_factory.nested_progress_bar()
302
merger = unshelver.make_merger(task)
303
merger.change_reporter = change_reporter
304
if self.apply_changes:
307
self.show_changes(merger)
310
if self.delete_shelf:
311
self.manager.delete_shelf(self.shelf_id)
313
for cleanup in reversed(cleanups):
316
def show_changes(self, merger):
317
"""Show the changes that this operation specifies."""
318
tree_merger = merger.make_merger()
319
# This implicitly shows the changes via the reporter, so we're done...
320
tt = tree_merger.make_preview_transform()