/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: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
from __future__ import absolute_import
18
17
 
 
18
from cStringIO import StringIO
19
19
import shutil
20
20
import sys
21
21
import tempfile
22
22
 
23
 
from io import BytesIO
24
 
 
25
 
from . import (
 
23
from bzrlib import (
26
24
    builtins,
27
25
    delta,
28
26
    diff,
36
34
    ui,
37
35
    workingtree,
38
36
)
39
 
from .i18n import gettext
40
37
 
41
38
 
42
39
class UseEditor(Exception):
45
42
 
46
43
class ShelfReporter(object):
47
44
 
48
 
    vocab = {'add file': gettext('Shelve adding file "%(path)s"?'),
49
 
             'binary': gettext('Shelve binary changes?'),
50
 
             'change kind': gettext('Shelve changing "%s" from %(other)s'
51
 
                                    ' to %(this)s?'),
52
 
             'delete file': gettext('Shelve removing file "%(path)s"?'),
53
 
             'final': gettext('Shelve %d change(s)?'),
54
 
             'hunk': gettext('Shelve?'),
55
 
             'modify target': gettext('Shelve changing target of'
56
 
                                      ' "%(path)s" from "%(other)s" to "%(this)s"?'),
57
 
             'rename': gettext('Shelve renaming "%(other)s" =>'
58
 
                               ' "%(this)s"?')
 
45
    vocab = {'add file': 'Shelve adding file "%(path)s"?',
 
46
             'binary': 'Shelve binary changes?',
 
47
             'change kind': 'Shelve changing "%s" from %(other)s'
 
48
             ' to %(this)s?',
 
49
             'delete file': 'Shelve removing file "%(path)s"?',
 
50
             'final': 'Shelve %d change(s)?',
 
51
             'hunk': 'Shelve?',
 
52
             'modify target': 'Shelve changing target of'
 
53
             ' "%(path)s" from "%(other)s" to "%(this)s"?',
 
54
             'rename': 'Shelve renaming "%(other)s" =>'
 
55
                        ' "%(this)s"?'
59
56
             }
60
57
 
61
58
    invert_diff = False
69
66
 
70
67
    def shelved_id(self, shelf_id):
71
68
        """Report the id changes were shelved to."""
72
 
        trace.note(gettext('Changes shelved with id "%d".') % shelf_id)
 
69
        trace.note('Changes shelved with id "%d".' % shelf_id)
73
70
 
74
71
    def changes_destroyed(self):
75
72
        """Report that changes were made without shelving."""
76
 
        trace.note(gettext('Selected changes destroyed.'))
 
73
        trace.note('Selected changes destroyed.')
77
74
 
78
75
    def selected_changes(self, transform):
79
76
        """Report the changes that were selected."""
80
 
        trace.note(gettext("Selected changes:"))
 
77
        trace.note("Selected changes:")
81
78
        changes = transform.iter_changes()
82
79
        delta.report_changes(changes, self.delta_reporter)
83
80
 
97
94
 
98
95
class ApplyReporter(ShelfReporter):
99
96
 
100
 
    vocab = {'add file': gettext('Delete file "%(path)s"?'),
101
 
             'binary': gettext('Apply binary changes?'),
102
 
             'change kind': gettext('Change "%(path)s" from %(this)s'
103
 
                                    ' to %(other)s?'),
104
 
             'delete file': gettext('Add file "%(path)s"?'),
105
 
             'final': gettext('Apply %d change(s)?'),
106
 
             'hunk': gettext('Apply change?'),
107
 
             'modify target': gettext('Change target of'
108
 
                                      ' "%(path)s" from "%(this)s" to "%(other)s"?'),
109
 
             'rename': gettext('Rename "%(this)s" => "%(other)s"?'),
 
97
    vocab = {'add file': 'Delete file "%(path)s"?',
 
98
             'binary': 'Apply binary changes?',
 
99
             'change kind': 'Change "%(path)s" from %(this)s'
 
100
             ' to %(other)s?',
 
101
             'delete file': 'Add file "%(path)s"?',
 
102
             'final': 'Apply %d change(s)?',
 
103
             'hunk': 'Apply change?',
 
104
             'modify target': 'Change target of'
 
105
             ' "%(path)s" from "%(this)s" to "%(other)s"?',
 
106
             'rename': 'Rename "%(this)s" => "%(other)s"?',
110
107
             }
111
108
 
112
109
    invert_diff = True
157
154
 
158
155
    @classmethod
159
156
    def from_args(klass, diff_writer, revision=None, all=False, file_list=None,
160
 
                  message=None, directory=None, destroy=False):
 
157
                  message=None, directory='.', destroy=False):
161
158
        """Create a shelver from commandline arguments.
162
159
 
163
160
        The returned shelver wil have a work_tree that is locked and should
171
168
        :param destroy: Change the working tree without storing the shelved
172
169
            changes.
173
170
        """
174
 
        if directory is None:
175
 
            directory = u'.'
176
 
        elif file_list:
177
 
            file_list = [osutils.pathjoin(directory, f) for f in file_list]
178
171
        tree, path = workingtree.WorkingTree.open_containing(directory)
179
172
        # Ensure that tree is locked for the lifetime of target_tree, as
180
173
        # target tree may be reading from the same dirstate.
181
174
        tree.lock_tree_write()
182
175
        try:
183
176
            target_tree = builtins._get_one_revision_tree('shelf2', revision,
184
 
                                                          tree.branch, tree)
185
 
            files = tree.safe_relpath_files(file_list)
 
177
                tree.branch, tree)
 
178
            files = builtins.safe_relpath_files(tree, file_list)
186
179
            return klass(tree, target_tree, diff_writer, all, all, files,
187
180
                         message, destroy)
188
181
        finally:
211
204
            if changes_shelved > 0:
212
205
                self.reporter.selected_changes(creator.work_transform)
213
206
                if (self.auto_apply or self.prompt_bool(
214
 
                        self.reporter.vocab['final'] % changes_shelved)):
 
207
                    self.reporter.vocab['final'] % changes_shelved)):
215
208
                    if self.destroy:
216
209
                        creator.transform()
217
210
                        self.reporter.changes_destroyed()
230
223
            self.change_editor.finish()
231
224
        self.work_tree.unlock()
232
225
 
 
226
 
233
227
    def get_parsed_patch(self, file_id, invert=False):
234
228
        """Return a parsed version of a file's patch.
235
229
 
238
232
            as removals, removals displayed as insertions).
239
233
        :return: A patches.Patch.
240
234
        """
241
 
        diff_file = BytesIO()
 
235
        diff_file = StringIO()
242
236
        if invert:
243
237
            old_tree = self.work_tree
244
238
            new_tree = self.target_tree
247
241
            new_tree = self.work_tree
248
242
        old_path = old_tree.id2path(file_id)
249
243
        new_path = new_tree.id2path(file_id)
250
 
        path_encoding = osutils.get_terminal_encoding()
251
 
        text_differ = diff.DiffText(old_tree, new_tree, diff_file,
252
 
                                    path_encoding=path_encoding)
253
 
        patch = text_differ.diff(old_path, new_path, 'file', 'file')
 
244
        text_differ = diff.DiffText(old_tree, new_tree, diff_file)
 
245
        patch = text_differ.diff(file_id, old_path, new_path, 'file', 'file')
254
246
        diff_file.seek(0)
255
247
        return patches.parse_patch(diff_file)
256
248
 
257
 
    def prompt(self, message, choices, default):
258
 
        return ui.ui_factory.choose(message, choices, default=default)
259
 
 
260
 
    def prompt_bool(self, question, allow_editor=False):
 
249
    def prompt(self, message):
 
250
        """Prompt the user for a character.
 
251
 
 
252
        :param message: The message to prompt a user with.
 
253
        :return: A character.
 
254
        """
 
255
        if not sys.stdin.isatty():
 
256
            # Since there is no controlling terminal we will hang when trying
 
257
            # to prompt the user, better abort now.  See
 
258
            # https://code.launchpad.net/~bialix/bzr/shelve-no-tty/+merge/14905
 
259
            # for more context.
 
260
            raise errors.BzrError("You need a controlling terminal.")
 
261
        sys.stdout.write(message)
 
262
        char = osutils.getchar()
 
263
        sys.stdout.write("\r" + ' ' * len(message) + '\r')
 
264
        sys.stdout.flush()
 
265
        return char
 
266
 
 
267
    def prompt_bool(self, question, long=False, allow_editor=False):
261
268
        """Prompt the user with a yes/no question.
262
269
 
263
270
        This may be overridden by self.auto.  It may also *set* self.auto.  It
267
274
        """
268
275
        if self.auto:
269
276
            return True
270
 
        alternatives_chars = 'yn'
271
 
        alternatives = '&yes\n&No'
272
 
        if allow_editor:
273
 
            alternatives_chars += 'e'
274
 
            alternatives += '\n&edit manually'
275
 
        alternatives_chars += 'fq'
276
 
        alternatives += '\n&finish\n&quit'
277
 
        choice = self.prompt(question, alternatives, 1)
278
 
        if choice is None:
279
 
            # EOF.
280
 
            char = 'n'
 
277
        editor_string = ''
 
278
        if long:
 
279
            if allow_editor:
 
280
                editor_string = '(E)dit manually, '
 
281
            prompt = ' [(y)es, (N)o, %s(f)inish, or (q)uit]' % editor_string
281
282
        else:
282
 
            char = alternatives_chars[choice]
 
283
            if allow_editor:
 
284
                editor_string = 'e'
 
285
            prompt = ' [yN%sfq?]' % editor_string
 
286
        char = self.prompt(question + prompt)
283
287
        if char == 'y':
284
288
            return True
285
289
        elif char == 'e' and allow_editor:
287
291
        elif char == 'f':
288
292
            self.auto = True
289
293
            return True
 
294
        elif char == '?':
 
295
            return self.prompt_bool(question, long=True)
290
296
        if char == 'q':
291
297
            raise errors.UserAbort()
292
298
        else:
299
305
        :param file_id: The id of the file that was modified.
300
306
        :return: The number of changes.
301
307
        """
302
 
        path = self.work_tree.id2path(file_id)
303
 
        work_tree_lines = self.work_tree.get_file_lines(path, file_id)
 
308
        work_tree_lines = self.work_tree.get_file_lines(file_id)
304
309
        try:
305
310
            lines, change_count = self._select_hunks(creator, file_id,
306
311
                                                     work_tree_lines)
324
329
        if self.reporter.invert_diff:
325
330
            target_lines = work_tree_lines
326
331
        else:
327
 
            path = self.target_tree.id2path(file_id)
328
 
            target_lines = self.target_tree.get_file_lines(path)
 
332
            target_lines = self.target_tree.get_file_lines(file_id)
329
333
        textfile.check_text_lines(work_tree_lines)
330
334
        textfile.check_text_lines(target_lines)
331
335
        parsed = self.get_parsed_patch(file_id, self.reporter.invert_diff)
334
338
            offset = 0
335
339
            self.diff_writer.write(parsed.get_header())
336
340
            for hunk in parsed.hunks:
337
 
                self.diff_writer.write(hunk.as_bytes())
 
341
                self.diff_writer.write(str(hunk))
338
342
                selected = self.prompt_bool(self.reporter.vocab['hunk'],
339
343
                                            allow_editor=(self.change_editor
340
344
                                                          is not None))
363
367
            content of the file, and change_region_count is the number of
364
368
            changed regions.
365
369
        """
366
 
        lines = osutils.split_lines(self.change_editor.edit_file(
367
 
            self.change_editor.old_tree.id2path(file_id),
368
 
            self.change_editor.new_tree.id2path(file_id)))
 
370
        lines = osutils.split_lines(self.change_editor.edit_file(file_id))
369
371
        return lines, self._count_changed_regions(work_tree_lines, lines)
370
372
 
371
373
    @staticmethod
401
403
                try:
402
404
                    shelf_id = int(shelf_id)
403
405
                except ValueError:
404
 
                    raise shelf.InvalidShelfId(shelf_id)
 
406
                    raise errors.InvalidShelfId(shelf_id)
405
407
            else:
406
408
                shelf_id = manager.last_shelf()
407
409
                if shelf_id is None:
408
 
                    raise errors.BzrCommandError(
409
 
                        gettext('No changes are shelved.'))
 
410
                    raise errors.BzrCommandError('No changes are shelved.')
410
411
            apply_changes = True
411
412
            delete_shelf = True
412
413
            read_shelf = True
464
465
        cleanups = [self.tree.unlock]
465
466
        try:
466
467
            if self.read_shelf:
467
 
                trace.note(gettext('Using changes with id "%d".') %
468
 
                           self.shelf_id)
 
468
                trace.note('Using changes with id "%d".' % self.shelf_id)
469
469
                unshelver = self.manager.get_unshelver(self.shelf_id)
470
470
                cleanups.append(unshelver.finalize)
471
471
                if unshelver.message is not None:
472
 
                    trace.note(gettext('Message: %s') % unshelver.message)
 
472
                    trace.note('Message: %s' % unshelver.message)
473
473
                change_reporter = delta._ChangeReporter()
474
 
                merger = unshelver.make_merger()
 
474
                merger = unshelver.make_merger(None)
475
475
                merger.change_reporter = change_reporter
476
476
                if self.apply_changes:
477
477
                    merger.do_merge()
481
481
                    self.show_changes(merger)
482
482
            if self.delete_shelf:
483
483
                self.manager.delete_shelf(self.shelf_id)
484
 
                trace.note(gettext('Deleted changes with id "%d".') %
485
 
                           self.shelf_id)
 
484
                trace.note('Deleted changes with id "%d".' % self.shelf_id)
486
485
        finally:
487
486
            for cleanup in reversed(cleanups):
488
487
                cleanup()
493
492
        tt = tree_merger.make_preview_transform()
494
493
        new_tree = tt.get_preview_tree()
495
494
        if self.write_diff_to is None:
496
 
            self.write_diff_to = ui.ui_factory.make_output_stream(
497
 
                encoding_type='exact')
498
 
        path_encoding = osutils.get_diff_header_encoding()
499
 
        diff.show_diff_trees(merger.this_tree, new_tree, self.write_diff_to,
500
 
                             path_encoding=path_encoding)
 
495
            self.write_diff_to = ui.ui_factory.make_output_stream()
 
496
        diff.show_diff_trees(merger.this_tree, new_tree, self.write_diff_to)
501
497
        tt.finalize()
502
498
 
503
499
    def show_changes(self, merger):