/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/shelf_ui.py

  • Committer: Aaron Bentley
  • Date: 2009-03-12 01:08:58 UTC
  • mto: This revision was merged to the branch mainline in revision 4127.
  • Revision ID: aaron@aaronbentley.com-20090312010858-hq6xx22l59nq4udp
Implement shelve --destroy

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2008 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
 
 
18
from cStringIO import StringIO
 
19
import shutil
 
20
import sys
 
21
import tempfile
 
22
 
 
23
from bzrlib import (
 
24
    builtins,
 
25
    delta,
 
26
    diff,
 
27
    errors,
 
28
    osutils,
 
29
    patches,
 
30
    shelf,
 
31
    textfile,
 
32
    trace,
 
33
    ui,
 
34
    workingtree,
 
35
)
 
36
 
 
37
 
 
38
class Shelver(object):
 
39
    """Interactively shelve the changes in a working tree."""
 
40
 
 
41
    def __init__(self, work_tree, target_tree, diff_writer=None, auto=False,
 
42
                 auto_apply=False, file_list=None, message=None,
 
43
                 destroy=False):
 
44
        """Constructor.
 
45
 
 
46
        :param work_tree: The working tree to shelve changes from.
 
47
        :param target_tree: The "unchanged" / old tree to compare the
 
48
            work_tree to.
 
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
        """
 
54
        self.work_tree = work_tree
 
55
        self.target_tree = target_tree
 
56
        self.diff_writer = diff_writer
 
57
        if self.diff_writer is None:
 
58
            self.diff_writer = sys.stdout
 
59
        self.manager = work_tree.get_shelf_manager()
 
60
        self.auto = auto
 
61
        self.auto_apply = auto_apply
 
62
        self.file_list = file_list
 
63
        self.message = message
 
64
        self.destroy = destroy
 
65
 
 
66
    @classmethod
 
67
    def from_args(klass, diff_writer, revision=None, all=False, file_list=None,
 
68
                  message=None, directory='.', destroy=False):
 
69
        """Create a shelver from commandline arguments.
 
70
 
 
71
        :param revision: RevisionSpec of the revision to compare to.
 
72
        :param all: If True, shelve all changes without prompting.
 
73
        :param file_list: If supplied, only files in this list may be  shelved.
 
74
        :param message: The message to associate with the shelved changes.
 
75
        :param directory: The directory containing the working tree.
 
76
        :param destroy: Change the working tree without storing the shelved
 
77
            changes.
 
78
        """
 
79
        tree, path = workingtree.WorkingTree.open_containing(directory)
 
80
        target_tree = builtins._get_one_revision_tree('shelf2', revision,
 
81
            tree.branch, tree)
 
82
        files = builtins.safe_relpath_files(tree, file_list)
 
83
        return klass(tree, target_tree, diff_writer, all, all, files, message,
 
84
                     destroy)
 
85
 
 
86
    def run(self):
 
87
        """Interactively shelve the changes."""
 
88
        creator = shelf.ShelfCreator(self.work_tree, self.target_tree,
 
89
                                     self.file_list)
 
90
        self.tempdir = tempfile.mkdtemp()
 
91
        changes_shelved = 0
 
92
        try:
 
93
            for change in creator.iter_shelvable():
 
94
                if change[0] == 'modify text':
 
95
                    try:
 
96
                        changes_shelved += self.handle_modify_text(creator,
 
97
                                                                   change[1])
 
98
                    except errors.BinaryFile:
 
99
                        if self.prompt_bool('Shelve binary changes?'):
 
100
                            changes_shelved += 1
 
101
                            creator.shelve_content_change(change[1])
 
102
                if change[0] == 'add file':
 
103
                    if self.prompt_bool('Shelve adding file "%s"?'
 
104
                                        % change[3]):
 
105
                        creator.shelve_creation(change[1])
 
106
                        changes_shelved += 1
 
107
                if change[0] == 'delete file':
 
108
                    if self.prompt_bool('Shelve removing file "%s"?'
 
109
                                        % change[3]):
 
110
                        creator.shelve_deletion(change[1])
 
111
                        changes_shelved += 1
 
112
                if change[0] == 'change kind':
 
113
                    if self.prompt_bool('Shelve changing "%s" from %s to %s? '
 
114
                                        % (change[4], change[2], change[3])):
 
115
                        creator.shelve_content_change(change[1])
 
116
                        changes_shelved += 1
 
117
                if change[0] == 'rename':
 
118
                    if self.prompt_bool('Shelve renaming "%s" => "%s"?' %
 
119
                                   change[2:]):
 
120
                        creator.shelve_rename(change[1])
 
121
                        changes_shelved += 1
 
122
            if changes_shelved > 0:
 
123
                trace.note("Selected changes:")
 
124
                changes = creator.work_transform.iter_changes()
 
125
                reporter = delta._ChangeReporter()
 
126
                delta.report_changes(changes, reporter)
 
127
                if (self.auto_apply or self.prompt_bool(
 
128
                    'Shelve %d change(s)?' % changes_shelved)):
 
129
                    if self.destroy:
 
130
                        creator.transform()
 
131
                    else:
 
132
                        shelf_id = self.manager.shelve_changes(creator,
 
133
                                                               self.message)
 
134
                        trace.note('Changes shelved with id "%d".' % shelf_id)
 
135
            else:
 
136
                trace.warning('No changes to shelve.')
 
137
        finally:
 
138
            shutil.rmtree(self.tempdir)
 
139
            creator.finalize()
 
140
 
 
141
    def get_parsed_patch(self, file_id):
 
142
        """Return a parsed version of a file's patch.
 
143
 
 
144
        :param file_id: The id of the file to generate a patch for.
 
145
        :return: A patches.Patch.
 
146
        """
 
147
        old_path = self.target_tree.id2path(file_id)
 
148
        new_path = self.work_tree.id2path(file_id)
 
149
        diff_file = StringIO()
 
150
        text_differ = diff.DiffText(self.target_tree, self.work_tree,
 
151
                                    diff_file)
 
152
        patch = text_differ.diff(file_id, old_path, new_path, 'file', 'file')
 
153
        diff_file.seek(0)
 
154
        return patches.parse_patch(diff_file)
 
155
 
 
156
    def prompt(self, message):
 
157
        """Prompt the user for a character.
 
158
 
 
159
        :param message: The message to prompt a user with.
 
160
        :return: A character.
 
161
        """
 
162
        sys.stdout.write(message)
 
163
        char = osutils.getchar()
 
164
        sys.stdout.write("\r" + ' ' * len(message) + '\r')
 
165
        sys.stdout.flush()
 
166
        return char
 
167
 
 
168
    def prompt_bool(self, question, long=False):
 
169
        """Prompt the user with a yes/no question.
 
170
 
 
171
        This may be overridden by self.auto.  It may also *set* self.auto.  It
 
172
        may also raise UserAbort.
 
173
        :param question: The question to ask the user.
 
174
        :return: True or False
 
175
        """
 
176
        if self.auto:
 
177
            return True
 
178
        if long:
 
179
            prompt = ' [(y)es, (N)o, (f)inish, or (q)uit]'
 
180
        else:
 
181
            prompt = ' [yNfq?]'
 
182
        char = self.prompt(question + prompt)
 
183
        if char == 'y':
 
184
            return True
 
185
        elif char == 'f':
 
186
            self.auto = True
 
187
            return True
 
188
        elif char == '?':
 
189
            return self.prompt_bool(question, long=True)
 
190
        if char == 'q':
 
191
            raise errors.UserAbort()
 
192
        else:
 
193
            return False
 
194
 
 
195
    def handle_modify_text(self, creator, file_id):
 
196
        """Provide diff hunk selection for modified text.
 
197
 
 
198
        :param creator: a ShelfCreator
 
199
        :param file_id: The id of the file to shelve.
 
200
        :return: number of shelved hunks.
 
201
        """
 
202
        target_lines = self.target_tree.get_file_lines(file_id)
 
203
        textfile.check_text_lines(self.work_tree.get_file_lines(file_id))
 
204
        textfile.check_text_lines(target_lines)
 
205
        parsed = self.get_parsed_patch(file_id)
 
206
        final_hunks = []
 
207
        if not self.auto:
 
208
            offset = 0
 
209
            self.diff_writer.write(parsed.get_header())
 
210
            for hunk in parsed.hunks:
 
211
                self.diff_writer.write(str(hunk))
 
212
                if not self.prompt_bool('Shelve?'):
 
213
                    hunk.mod_pos += offset
 
214
                    final_hunks.append(hunk)
 
215
                else:
 
216
                    offset -= (hunk.mod_range - hunk.orig_range)
 
217
        sys.stdout.flush()
 
218
        if len(parsed.hunks) == len(final_hunks):
 
219
            return 0
 
220
        patched = patches.iter_patched_from_hunks(target_lines, final_hunks)
 
221
        creator.shelve_lines(file_id, list(patched))
 
222
        return len(parsed.hunks) - len(final_hunks)
 
223
 
 
224
 
 
225
class Unshelver(object):
 
226
    """Unshelve changes into a working tree."""
 
227
 
 
228
    @classmethod
 
229
    def from_args(klass, shelf_id=None, action='apply', directory='.'):
 
230
        """Create an unshelver from commandline arguments.
 
231
 
 
232
        :param shelf_id: Integer id of the shelf, as a string.
 
233
        :param action: action to perform.  May be 'apply', 'dry-run',
 
234
            'delete'.
 
235
        :param directory: The directory to unshelve changes into.
 
236
        """
 
237
        tree, path = workingtree.WorkingTree.open_containing(directory)
 
238
        manager = tree.get_shelf_manager()
 
239
        if shelf_id is not None:
 
240
            try:
 
241
                shelf_id = int(shelf_id)
 
242
            except ValueError:
 
243
                raise errors.InvalidShelfId(shelf_id)
 
244
        else:
 
245
            shelf_id = manager.last_shelf()
 
246
            if shelf_id is None:
 
247
                raise errors.BzrCommandError('No changes are shelved.')
 
248
            trace.note('Unshelving changes with id "%d".' % shelf_id)
 
249
        apply_changes = True
 
250
        delete_shelf = True
 
251
        read_shelf = True
 
252
        if action == 'dry-run':
 
253
            apply_changes = False
 
254
            delete_shelf = False
 
255
        if action == 'delete-only':
 
256
            apply_changes = False
 
257
            read_shelf = False
 
258
        return klass(tree, manager, shelf_id, apply_changes, delete_shelf,
 
259
                     read_shelf)
 
260
 
 
261
    def __init__(self, tree, manager, shelf_id, apply_changes=True,
 
262
                 delete_shelf=True, read_shelf=True):
 
263
        """Constructor.
 
264
 
 
265
        :param tree: The working tree to unshelve into.
 
266
        :param manager: The ShelveManager containing the shelved changes.
 
267
        :param shelf_id:
 
268
        :param apply_changes: If True, apply the shelved changes to the
 
269
            working tree.
 
270
        :param delete_shelf: If True, delete the changes from the shelf.
 
271
        :param read_shelf: If True, read the changes from the shelf.
 
272
        """
 
273
        self.tree = tree
 
274
        manager = tree.get_shelf_manager()
 
275
        self.manager = manager
 
276
        self.shelf_id = shelf_id
 
277
        self.apply_changes = apply_changes
 
278
        self.delete_shelf = delete_shelf
 
279
        self.read_shelf = read_shelf
 
280
 
 
281
    def run(self):
 
282
        """Perform the unshelving operation."""
 
283
        self.tree.lock_write()
 
284
        cleanups = [self.tree.unlock]
 
285
        try:
 
286
            if self.read_shelf:
 
287
                unshelver = self.manager.get_unshelver(self.shelf_id)
 
288
                cleanups.append(unshelver.finalize)
 
289
                if unshelver.message is not None:
 
290
                    trace.note('Message: %s' % unshelver.message)
 
291
                change_reporter = delta._ChangeReporter()
 
292
                task = ui.ui_factory.nested_progress_bar()
 
293
                try:
 
294
                    merger = unshelver.make_merger(task)
 
295
                    merger.change_reporter = change_reporter
 
296
                    if self.apply_changes:
 
297
                        merger.do_merge()
 
298
                    else:
 
299
                        self.show_changes(merger)
 
300
                finally:
 
301
                    task.finished()
 
302
            if self.delete_shelf:
 
303
                self.manager.delete_shelf(self.shelf_id)
 
304
        finally:
 
305
            for cleanup in reversed(cleanups):
 
306
                cleanup()
 
307
 
 
308
    def show_changes(self, merger):
 
309
        """Show the changes that this operation specifies."""
 
310
        tree_merger = merger.make_merger()
 
311
        # This implicitly shows the changes via the reporter, so we're done...
 
312
        tt = tree_merger.make_preview_transform()
 
313
        tt.finalize()