/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: Jonathan Lange
  • Date: 2009-12-09 09:20:42 UTC
  • mfrom: (4881 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4907.
  • Revision ID: jml@canonical.com-20091209092042-s2zgqcf8f39yzxpj
Merge trunk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
22
22
 
23
23
from bzrlib import (
24
24
    builtins,
 
25
    commands,
25
26
    delta,
26
27
    diff,
27
28
    errors,
28
29
    osutils,
29
30
    patches,
 
31
    patiencediff,
30
32
    shelf,
31
33
    textfile,
32
34
    trace,
35
37
)
36
38
 
37
39
 
 
40
class UseEditor(Exception):
 
41
    """Use an editor instead of selecting hunks."""
 
42
 
 
43
 
38
44
class ShelfReporter(object):
39
45
 
 
46
    vocab = {'add file': 'Shelve adding file "%(path)s"?',
 
47
             'binary': 'Shelve binary changes?',
 
48
             'change kind': 'Shelve changing "%s" from %(other)s'
 
49
             ' to %(this)s?',
 
50
             'delete file': 'Shelve removing file "%(path)s"?',
 
51
             'final': 'Shelve %d change(s)?',
 
52
             'hunk': 'Shelve?',
 
53
             'modify target': 'Shelve changing target of'
 
54
             ' "%(path)s" from "%(other)s" to "%(this)s"?',
 
55
             'rename': 'Shelve renaming "%(other)s" =>'
 
56
                        ' "%(this)s"?'
 
57
             }
 
58
 
 
59
    invert_diff = False
 
60
 
40
61
    def __init__(self):
41
62
        self.delta_reporter = delta._ChangeReporter()
42
63
 
43
64
    def no_changes(self):
 
65
        """Report that no changes were selected to apply."""
44
66
        trace.warning('No changes to shelve.')
45
67
 
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)
48
71
 
 
72
    def changes_destroyed(self):
 
73
        """Report that changes were made without shelving."""
 
74
        trace.note('Selected changes destroyed.')
 
75
 
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)
53
81
 
 
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]}
 
90
        else:
 
91
            vals = {'path': change[3]}
 
92
        prompt = self.vocab[change[0]] % vals
 
93
        return prompt
 
94
 
 
95
 
 
96
class ApplyReporter(ShelfReporter):
 
97
 
 
98
    vocab = {'add file': 'Delete file "%(path)s"?',
 
99
             'binary': 'Apply binary changes?',
 
100
             'change kind': 'Change "%(path)s" from %(this)s'
 
101
             ' to %(other)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"?',
 
108
             }
 
109
 
 
110
    invert_diff = True
 
111
 
 
112
    def changes_destroyed(self):
 
113
        pass
 
114
 
54
115
 
55
116
class Shelver(object):
56
117
    """Interactively shelve the changes in a working tree."""
70
131
        :param destroy: Change the working tree without storing the shelved
71
132
            changes.
72
133
        :param manager: The shelf manager to use.
 
134
        :param reporter: Object for reporting changes to user.
73
135
        """
74
136
        self.work_tree = work_tree
75
137
        self.target_tree = target_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()
90
155
 
91
156
    @classmethod
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.
95
160
 
 
161
        The returned shelver wil have a work_tree that is locked and should
 
162
        be unlocked.
 
163
 
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.
102
170
            changes.
103
171
        """
104
172
        tree, path = workingtree.WorkingTree.open_containing(directory)
105
 
        target_tree = builtins._get_one_revision_tree('shelf2', revision,
106
 
            tree.branch, tree)
107
 
        files = builtins.safe_relpath_files(tree, file_list)
108
 
        return klass(tree, target_tree, diff_writer, all, all, files, message,
109
 
                     destroy)
 
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()
 
176
        try:
 
177
            target_tree = builtins._get_one_revision_tree('shelf2', revision,
 
178
                tree.branch, tree)
 
179
            files = builtins.safe_relpath_files(tree, file_list)
 
180
            return klass(tree, target_tree, diff_writer, all, all, files,
 
181
                         message, destroy)
 
182
        finally:
 
183
            tree.unlock()
110
184
 
111
185
    def run(self):
112
186
        """Interactively shelve the changes."""
121
195
                        changes_shelved += self.handle_modify_text(creator,
122
196
                                                                   change[1])
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"?'
129
 
                                        % change[3]):
130
 
                        creator.shelve_creation(change[1])
131
 
                        changes_shelved += 1
132
 
                if change[0] == 'delete file':
133
 
                    if self.prompt_bool('Shelve removing file "%s"?'
134
 
                                        % change[3]):
135
 
                        creator.shelve_deletion(change[1])
136
 
                        changes_shelved += 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])
141
 
                        changes_shelved += 1
142
 
                if change[0] == 'rename':
143
 
                    if self.prompt_bool('Shelve renaming "%s" => "%s"?' %
144
 
                                   change[2:]):
145
 
                        creator.shelve_rename(change[1])
146
 
                        changes_shelved += 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])
 
201
                else:
 
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)):
156
209
                    if self.destroy:
157
210
                        creator.transform()
158
 
                        trace.note('Selected changes destroyed.')
 
211
                        self.reporter.changes_destroyed()
159
212
                    else:
160
213
                        shelf_id = self.manager.shelve_changes(creator,
161
214
                                                               self.message)
166
219
            shutil.rmtree(self.tempdir)
167
220
            creator.finalize()
168
221
 
169
 
    def get_parsed_patch(self, file_id):
 
222
    def finalize(self):
 
223
        if self.change_editor is not None:
 
224
            self.change_editor.finish()
 
225
        self.work_tree.unlock()
 
226
 
 
227
 
 
228
    def get_parsed_patch(self, file_id, invert=False):
170
229
        """Return a parsed version of a file's patch.
171
230
 
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.
174
235
        """
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,
179
 
                                    diff_file)
 
237
        if invert:
 
238
            old_tree = self.work_tree
 
239
            new_tree = self.target_tree
 
240
        else:
 
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.
189
255
        """
 
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
 
260
            # for more context.
 
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()
194
266
        return char
195
267
 
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.
198
270
 
199
271
        This may be overridden by self.auto.  It may also *set* self.auto.  It
203
275
        """
204
276
        if self.auto:
205
277
            return True
 
278
        editor_string = ''
206
279
        if long:
207
 
            prompt = ' [(y)es, (N)o, (f)inish, or (q)uit]'
 
280
            if allow_editor:
 
281
                editor_string = '(E)dit manually, '
 
282
            prompt = ' [(y)es, (N)o, %s(f)inish, or (q)uit]' % editor_string
208
283
        else:
209
 
            prompt = ' [yNfq?]'
 
284
            if allow_editor:
 
285
                editor_string = 'e'
 
286
            prompt = ' [yN%sfq?]' % editor_string
210
287
        char = self.prompt(question + prompt)
211
288
        if char == 'y':
212
289
            return True
 
290
        elif char == 'e' and allow_editor:
 
291
            raise UseEditor
213
292
        elif char == 'f':
214
293
            self.auto = True
215
294
            return True
221
300
            return False
222
301
 
223
302
    def handle_modify_text(self, creator, file_id):
 
303
        """Handle modified text, by using hunk selection or file editing.
 
304
 
 
305
        :param creator: A ShelfCreator.
 
306
        :param file_id: The id of the file that was modified.
 
307
        :return: The number of changes.
 
308
        """
 
309
        work_tree_lines = self.work_tree.get_file_lines(file_id)
 
310
        try:
 
311
            lines, change_count = self._select_hunks(creator, file_id,
 
312
                                                     work_tree_lines)
 
313
        except UseEditor:
 
314
            lines, change_count = self._edit_file(file_id, work_tree_lines)
 
315
        if change_count != 0:
 
316
            creator.shelve_lines(file_id, lines)
 
317
        return change_count
 
318
 
 
319
    def _select_hunks(self, creator, file_id, work_tree_lines):
224
320
        """Provide diff hunk selection for modified text.
225
321
 
 
322
        If self.reporter.invert_diff is True, the diff is inverted so that
 
323
        insertions are displayed as removals and vice versa.
 
324
 
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.
229
329
        """
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
 
332
        else:
 
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)
234
337
        final_hunks = []
235
338
        if not self.auto:
236
339
            offset = 0
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
 
345
                                                          is not None))
 
346
                if not self.reporter.invert_diff:
 
347
                    selected = (not selected)
 
348
                if selected:
241
349
                    hunk.mod_pos += offset
242
350
                    final_hunks.append(hunk)
243
351
                else:
244
352
                    offset -= (hunk.mod_range - hunk.orig_range)
245
353
        sys.stdout.flush()
246
 
        if len(parsed.hunks) == len(final_hunks):
247
 
            return 0
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)
 
356
        else:
 
357
            change_count = len(parsed.hunks) - len(final_hunks)
 
358
        patched = patches.iter_patched_from_hunks(target_lines,
 
359
                                                  final_hunks)
 
360
        lines = list(patched)
 
361
        return lines, change_count
 
362
 
 
363
    def _edit_file(self, file_id, work_tree_lines):
 
364
        """
 
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
 
369
            changed regions.
 
370
        """
 
371
        lines = osutils.split_lines(self.change_editor.edit_file(file_id))
 
372
        return lines, self._count_changed_regions(work_tree_lines, lines)
 
373
 
 
374
    @staticmethod
 
375
    def _count_changed_regions(old_lines, new_lines):
 
376
        matcher = patiencediff.PatienceSequenceMatcher(None, old_lines,
 
377
                                                       new_lines)
 
378
        blocks = matcher.get_matching_blocks()
 
379
        return len(blocks) - 2
251
380
 
252
381
 
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.
259
388
 
 
389
        The returned shelver wil have a tree that is locked and should
 
390
        be unlocked.
 
391
 
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',
262
394
            'delete'.
263
395
        :param directory: The directory to unshelve changes into.
264
396
        """
265
397
        tree, path = workingtree.WorkingTree.open_containing(directory)
266
 
        manager = tree.get_shelf_manager()
267
 
        if shelf_id is not None:
268
 
            try:
269
 
                shelf_id = int(shelf_id)
270
 
            except ValueError:
271
 
                raise errors.InvalidShelfId(shelf_id)
272
 
        else:
273
 
            shelf_id = manager.last_shelf()
274
 
            if shelf_id is None:
275
 
                raise errors.BzrCommandError('No changes are shelved.')
276
 
            trace.note('Unshelving changes with id "%d".' % shelf_id)
277
 
        apply_changes = True
278
 
        delete_shelf = True
279
 
        read_shelf = True
280
 
        if action == 'dry-run':
281
 
            apply_changes = False
282
 
            delete_shelf = False
283
 
        if action == 'delete-only':
284
 
            apply_changes = False
285
 
            read_shelf = False
 
398
        tree.lock_tree_write()
 
399
        try:
 
400
            manager = tree.get_shelf_manager()
 
401
            if shelf_id is not None:
 
402
                try:
 
403
                    shelf_id = int(shelf_id)
 
404
                except ValueError:
 
405
                    raise errors.InvalidShelfId(shelf_id)
 
406
            else:
 
407
                shelf_id = manager.last_shelf()
 
408
                if shelf_id is None:
 
409
                    raise errors.BzrCommandError('No changes are shelved.')
 
410
                trace.note('Unshelving changes with id "%d".' % shelf_id)
 
411
            apply_changes = True
 
412
            delete_shelf = True
 
413
            read_shelf = True
 
414
            if action == 'dry-run':
 
415
                apply_changes = False
 
416
                delete_shelf = False
 
417
            if action == 'delete-only':
 
418
                apply_changes = False
 
419
                read_shelf = False
 
420
        except:
 
421
            tree.unlock()
 
422
            raise
286
423
        return klass(tree, manager, shelf_id, apply_changes, delete_shelf,
287
424
                     read_shelf)
288
425
 
308
445
 
309
446
    def run(self):
310
447
        """Perform the unshelving operation."""
311
 
        self.tree.lock_write()
 
448
        self.tree.lock_tree_write()
312
449
        cleanups = [self.tree.unlock]
313
450
        try:
314
451
            if self.read_shelf: