/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 breezy/tests/blackbox/test_commit.py

  • Committer: Breezy landing bot
  • Author(s): Jelmer Vernooij
  • Date: 2018-11-16 18:26:22 UTC
  • mfrom: (7167.1.4 run-flake8)
  • Revision ID: breezy.the.bot@gmail.com-20181116182622-qw3gan3hz78a2imw
Add a flake8 test.

Merged from https://code.launchpad.net/~jelmer/brz/run-flake8/+merge/358902

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006-2012, 2016 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
 
 
18
"""Tests for the commit CLI of bzr."""
 
19
 
 
20
import doctest
 
21
import os
 
22
import re
 
23
import sys
 
24
 
 
25
from testtools.matchers import DocTestMatches
 
26
 
 
27
from ... import (
 
28
    config,
 
29
    osutils,
 
30
    ignores,
 
31
    msgeditor,
 
32
    )
 
33
from ...controldir import ControlDir
 
34
from ...sixish import PY3
 
35
from .. import (
 
36
    test_foreign,
 
37
    features,
 
38
    )
 
39
from .. import TestCaseWithTransport
 
40
from ..matchers import ContainsNoVfsCalls
 
41
 
 
42
 
 
43
class TestCommit(TestCaseWithTransport):
 
44
 
 
45
    def test_05_empty_commit(self):
 
46
        """Commit of tree with no versioned files should fail"""
 
47
        # If forced, it should succeed, but this is not tested here.
 
48
        self.make_branch_and_tree('.')
 
49
        self.build_tree(['hello.txt'])
 
50
        out, err = self.run_bzr('commit -m empty', retcode=3)
 
51
        self.assertEqual('', out)
 
52
        # Two ugly bits here.
 
53
        # 1) We really don't want 'aborting commit write group' anymore.
 
54
        # 2) brz: ERROR: is a really long line, so we wrap it with '\'
 
55
        self.assertThat(
 
56
            err,
 
57
            DocTestMatches("""\
 
58
Committing to: ...
 
59
brz: ERROR: No changes to commit.\
 
60
 Please 'brz add' the files you want to commit,\
 
61
 or use --unchanged to force an empty commit.
 
62
""", flags=doctest.ELLIPSIS|doctest.REPORT_UDIFF))
 
63
 
 
64
    def test_commit_success(self):
 
65
        """Successful commit should not leave behind a bzr-commit-* file"""
 
66
        self.make_branch_and_tree('.')
 
67
        self.run_bzr('commit --unchanged -m message')
 
68
        self.assertEqual('', self.run_bzr('unknowns')[0])
 
69
 
 
70
        # same for unicode messages
 
71
        self.run_bzr(["commit", "--unchanged", "-m", u'foo\xb5'])
 
72
        self.assertEqual('', self.run_bzr('unknowns')[0])
 
73
 
 
74
    def test_commit_lossy_native(self):
 
75
        """A --lossy option to commit is supported."""
 
76
        self.make_branch_and_tree('.')
 
77
        self.run_bzr('commit --lossy --unchanged -m message')
 
78
        self.assertEqual('', self.run_bzr('unknowns')[0])
 
79
 
 
80
    def test_commit_lossy_foreign(self):
 
81
        test_foreign.register_dummy_foreign_for_test(self)
 
82
        self.make_branch_and_tree('.',
 
83
            format=test_foreign.DummyForeignVcsDirFormat())
 
84
        self.run_bzr('commit --lossy --unchanged -m message')
 
85
        output = self.run_bzr('revision-info')[0]
 
86
        self.assertTrue(output.startswith('1 dummy-'))
 
87
 
 
88
    def test_commit_with_path(self):
 
89
        """Commit tree with path of root specified"""
 
90
        a_tree = self.make_branch_and_tree('a')
 
91
        self.build_tree(['a/a_file'])
 
92
        a_tree.add('a_file')
 
93
        self.run_bzr(['commit', '-m', 'first commit', 'a'])
 
94
 
 
95
        b_tree = a_tree.controldir.sprout('b').open_workingtree()
 
96
        self.build_tree_contents([('b/a_file', b'changes in b')])
 
97
        self.run_bzr(['commit', '-m', 'first commit in b', 'b'])
 
98
 
 
99
        self.build_tree_contents([('a/a_file', b'new contents')])
 
100
        self.run_bzr(['commit', '-m', 'change in a', 'a'])
 
101
 
 
102
        b_tree.merge_from_branch(a_tree.branch)
 
103
        self.assertEqual(len(b_tree.conflicts()), 1)
 
104
        self.run_bzr('resolved b/a_file')
 
105
        self.run_bzr(['commit', '-m', 'merge into b', 'b'])
 
106
 
 
107
    def test_10_verbose_commit(self):
 
108
        """Add one file and examine verbose commit output"""
 
109
        tree = self.make_branch_and_tree('.')
 
110
        self.build_tree(['hello.txt'])
 
111
        tree.add("hello.txt")
 
112
        out, err = self.run_bzr('commit -m added')
 
113
        self.assertEqual('', out)
 
114
        self.assertContainsRe(err, '^Committing to: .*\n'
 
115
                              'added hello.txt\n'
 
116
                              'Committed revision 1.\n$',)
 
117
 
 
118
    def prepare_simple_history(self):
 
119
        """Prepare and return a working tree with one commit of one file"""
 
120
        # Commit with modified file should say so
 
121
        wt = ControlDir.create_standalone_workingtree('.')
 
122
        self.build_tree(['hello.txt', 'extra.txt'])
 
123
        wt.add(['hello.txt'])
 
124
        wt.commit(message='added')
 
125
        return wt
 
126
 
 
127
    def test_verbose_commit_modified(self):
 
128
        # Verbose commit of modified file should say so
 
129
        wt = self.prepare_simple_history()
 
130
        self.build_tree_contents([('hello.txt', b'new contents')])
 
131
        out, err = self.run_bzr('commit -m modified')
 
132
        self.assertEqual('', out)
 
133
        self.assertContainsRe(err, '^Committing to: .*\n'
 
134
                              'modified hello\\.txt\n'
 
135
                              'Committed revision 2\\.\n$')
 
136
 
 
137
    def test_unicode_commit_message_is_filename(self):
 
138
        """Unicode commit message same as a filename (Bug #563646).
 
139
        """
 
140
        self.requireFeature(features.UnicodeFilenameFeature)
 
141
        file_name = u'\N{euro sign}'
 
142
        self.run_bzr(['init'])
 
143
        with open(file_name, 'w') as f:
 
144
            f.write('hello world')
 
145
        self.run_bzr(['add'])
 
146
        out, err = self.run_bzr(['commit', '-m', file_name])
 
147
        reflags = re.MULTILINE|re.DOTALL|re.UNICODE
 
148
        te = osutils.get_terminal_encoding()
 
149
        self.assertContainsRe(err if PY3 else err.decode(te),
 
150
            u'The commit message is a file name:',
 
151
            flags=reflags)
 
152
 
 
153
        # Run same test with a filename that causes encode
 
154
        # error for the terminal encoding. We do this
 
155
        # by forcing terminal encoding of ascii for
 
156
        # osutils.get_terminal_encoding which is used
 
157
        # by ui.text.show_warning
 
158
        default_get_terminal_enc = osutils.get_terminal_encoding
 
159
        try:
 
160
            osutils.get_terminal_encoding = lambda trace=None: 'ascii'
 
161
            file_name = u'foo\u1234'
 
162
            with open(file_name, 'w') as f:
 
163
                f.write('hello world')
 
164
            self.run_bzr(['add'])
 
165
            out, err = self.run_bzr(['commit', '-m', file_name])
 
166
            reflags = re.MULTILINE|re.DOTALL|re.UNICODE
 
167
            te = osutils.get_terminal_encoding()
 
168
            self.assertContainsRe(err if PY3 else err.decode(te, 'replace'),
 
169
                u'The commit message is a file name:',
 
170
                flags=reflags)
 
171
        finally:
 
172
            osutils.get_terminal_encoding = default_get_terminal_enc
 
173
 
 
174
    def test_non_ascii_file_unversioned_utf8(self):
 
175
        self.requireFeature(features.UnicodeFilenameFeature)
 
176
        tree = self.make_branch_and_tree(".")
 
177
        self.build_tree(["f"])
 
178
        tree.add(["f"])
 
179
        out, err = self.run_bzr_raw(["commit", "-m", "Wrong filename", u"\xa7"],
 
180
            encoding="utf-8", retcode=3)
 
181
        self.assertContainsRe(err, b"(?m)not versioned: \"\xc2\xa7\"$")
 
182
 
 
183
    def test_non_ascii_file_unversioned_iso_8859_5(self):
 
184
        self.requireFeature(features.UnicodeFilenameFeature)
 
185
        tree = self.make_branch_and_tree(".")
 
186
        self.build_tree(["f"])
 
187
        tree.add(["f"])
 
188
        out, err = self.run_bzr_raw(["commit", "-m", "Wrong filename", u"\xa7"],
 
189
            encoding="iso-8859-5", retcode=3)
 
190
        if not PY3:
 
191
            self.expectFailure("Error messages are always written as UTF-8",
 
192
                self.assertNotContainsString, err, b"\xc2\xa7")
 
193
        else:
 
194
            self.assertNotContainsString(err, b"\xc2\xa7")
 
195
        self.assertContainsRe(err, b"(?m)not versioned: \"\xfd\"$")
 
196
 
 
197
    def test_warn_about_forgotten_commit_message(self):
 
198
        """Test that the lack of -m parameter is caught"""
 
199
        wt = self.make_branch_and_tree('.')
 
200
        self.build_tree(['one', 'two'])
 
201
        wt.add(['two'])
 
202
        out, err = self.run_bzr('commit -m one two')
 
203
        self.assertContainsRe(err, "The commit message is a file name")
 
204
 
 
205
    def test_verbose_commit_renamed(self):
 
206
        # Verbose commit of renamed file should say so
 
207
        wt = self.prepare_simple_history()
 
208
        wt.rename_one('hello.txt', 'gutentag.txt')
 
209
        out, err = self.run_bzr('commit -m renamed')
 
210
        self.assertEqual('', out)
 
211
        self.assertContainsRe(err, '^Committing to: .*\n'
 
212
                              'renamed hello\\.txt => gutentag\\.txt\n'
 
213
                              'Committed revision 2\\.$\n')
 
214
 
 
215
    def test_verbose_commit_moved(self):
 
216
        # Verbose commit of file moved to new directory should say so
 
217
        wt = self.prepare_simple_history()
 
218
        os.mkdir('subdir')
 
219
        wt.add(['subdir'])
 
220
        wt.rename_one('hello.txt', 'subdir/hello.txt')
 
221
        out, err = self.run_bzr('commit -m renamed')
 
222
        self.assertEqual('', out)
 
223
        self.assertEqual({
 
224
            'Committing to: %s/' % osutils.getcwd(),
 
225
            'added subdir',
 
226
            'renamed hello.txt => subdir/hello.txt',
 
227
            'Committed revision 2.',
 
228
            '',
 
229
            }, set(err.split('\n')))
 
230
 
 
231
    def test_verbose_commit_with_unknown(self):
 
232
        """Unknown files should not be listed by default in verbose output"""
 
233
        # Is that really the best policy?
 
234
        wt = ControlDir.create_standalone_workingtree('.')
 
235
        self.build_tree(['hello.txt', 'extra.txt'])
 
236
        wt.add(['hello.txt'])
 
237
        out, err = self.run_bzr('commit -m added')
 
238
        self.assertEqual('', out)
 
239
        self.assertContainsRe(err, '^Committing to: .*\n'
 
240
                              'added hello\\.txt\n'
 
241
                              'Committed revision 1\\.\n$')
 
242
 
 
243
    def test_verbose_commit_with_unchanged(self):
 
244
        """Unchanged files should not be listed by default in verbose output"""
 
245
        tree = self.make_branch_and_tree('.')
 
246
        self.build_tree(['hello.txt', 'unchanged.txt'])
 
247
        tree.add('unchanged.txt')
 
248
        self.run_bzr('commit -m unchanged unchanged.txt')
 
249
        tree.add("hello.txt")
 
250
        out, err = self.run_bzr('commit -m added')
 
251
        self.assertEqual('', out)
 
252
        self.assertContainsRe(err, '^Committing to: .*\n'
 
253
                              'added hello\\.txt\n'
 
254
                              'Committed revision 2\\.$\n')
 
255
 
 
256
    def test_verbose_commit_includes_master_location(self):
 
257
        """Location of master is displayed when committing to bound branch"""
 
258
        a_tree = self.make_branch_and_tree('a')
 
259
        self.build_tree(['a/b'])
 
260
        a_tree.add('b')
 
261
        a_tree.commit(message='Initial message')
 
262
 
 
263
        b_tree = a_tree.branch.create_checkout('b')
 
264
        expected = "%s/" % (osutils.abspath('a'), )
 
265
        out, err = self.run_bzr('commit -m blah --unchanged', working_dir='b')
 
266
        self.assertEqual(err, 'Committing to: %s\n'
 
267
                         'Committed revision 2.\n' % expected)
 
268
 
 
269
    def test_commit_sanitizes_CR_in_message(self):
 
270
        # See bug #433779, basically Emacs likes to pass '\r\n' style line
 
271
        # endings to 'brz commit -m ""' which breaks because we don't allow
 
272
        # '\r' in commit messages. (Mostly because of issues where XML style
 
273
        # formats arbitrarily strip it out of the data while parsing.)
 
274
        # To make life easier for users, we just always translate '\r\n' =>
 
275
        # '\n'. And '\r' => '\n'.
 
276
        a_tree = self.make_branch_and_tree('a')
 
277
        self.build_tree(['a/b'])
 
278
        a_tree.add('b')
 
279
        self.run_bzr(['commit',
 
280
                      '-m', 'a string\r\n\r\nwith mixed\r\rendings\n'],
 
281
                     working_dir='a')
 
282
        rev_id = a_tree.branch.last_revision()
 
283
        rev = a_tree.branch.repository.get_revision(rev_id)
 
284
        self.assertEqualDiff('a string\n\nwith mixed\n\nendings\n',
 
285
                             rev.message)
 
286
 
 
287
    def test_commit_merge_reports_all_modified_files(self):
 
288
        # the commit command should show all the files that are shown by
 
289
        # brz diff or brz status when committing, even when they were not
 
290
        # changed by the user but rather through doing a merge.
 
291
        this_tree = self.make_branch_and_tree('this')
 
292
        # we need a bunch of files and dirs, to perform one action on each.
 
293
        self.build_tree([
 
294
            'this/dirtorename/',
 
295
            'this/dirtoreparent/',
 
296
            'this/dirtoleave/',
 
297
            'this/dirtoremove/',
 
298
            'this/filetoreparent',
 
299
            'this/filetorename',
 
300
            'this/filetomodify',
 
301
            'this/filetoremove',
 
302
            'this/filetoleave']
 
303
            )
 
304
        this_tree.add([
 
305
            'dirtorename',
 
306
            'dirtoreparent',
 
307
            'dirtoleave',
 
308
            'dirtoremove',
 
309
            'filetoreparent',
 
310
            'filetorename',
 
311
            'filetomodify',
 
312
            'filetoremove',
 
313
            'filetoleave']
 
314
            )
 
315
        this_tree.commit('create_files')
 
316
        other_dir = this_tree.controldir.sprout('other')
 
317
        other_tree = other_dir.open_workingtree()
 
318
        other_tree.lock_write()
 
319
        # perform the needed actions on the files and dirs.
 
320
        try:
 
321
            other_tree.rename_one('dirtorename', 'renameddir')
 
322
            other_tree.rename_one('dirtoreparent', 'renameddir/reparenteddir')
 
323
            other_tree.rename_one('filetorename', 'renamedfile')
 
324
            other_tree.rename_one('filetoreparent',
 
325
                                  'renameddir/reparentedfile')
 
326
            other_tree.remove(['dirtoremove', 'filetoremove'])
 
327
            self.build_tree_contents([
 
328
                ('other/newdir/',),
 
329
                ('other/filetomodify', b'new content'),
 
330
                ('other/newfile', b'new file content')])
 
331
            other_tree.add('newfile')
 
332
            other_tree.add('newdir/')
 
333
            other_tree.commit('modify all sample files and dirs.')
 
334
        finally:
 
335
            other_tree.unlock()
 
336
        this_tree.merge_from_branch(other_tree.branch)
 
337
        out, err = self.run_bzr('commit -m added', working_dir='this')
 
338
        self.assertEqual('', out)
 
339
        self.assertEqual({
 
340
            'Committing to: %s/' % osutils.pathjoin(osutils.getcwd(), 'this'),
 
341
            'modified filetomodify',
 
342
            'added newdir',
 
343
            'added newfile',
 
344
            'renamed dirtorename => renameddir',
 
345
            'renamed filetorename => renamedfile',
 
346
            'renamed dirtoreparent => renameddir/reparenteddir',
 
347
            'renamed filetoreparent => renameddir/reparentedfile',
 
348
            'deleted dirtoremove',
 
349
            'deleted filetoremove',
 
350
            'Committed revision 2.',
 
351
            ''
 
352
            }, set(err.split('\n')))
 
353
 
 
354
    def test_empty_commit_message(self):
 
355
        tree = self.make_branch_and_tree('.')
 
356
        self.build_tree_contents([('foo.c', b'int main() {}')])
 
357
        tree.add('foo.c')
 
358
        self.run_bzr('commit -m ""')
 
359
 
 
360
    def test_other_branch_commit(self):
 
361
        # this branch is to ensure consistent behaviour, whether we're run
 
362
        # inside a branch, or not.
 
363
        outer_tree = self.make_branch_and_tree('.')
 
364
        inner_tree = self.make_branch_and_tree('branch')
 
365
        self.build_tree_contents([
 
366
            ('branch/foo.c', b'int main() {}'),
 
367
            ('branch/bar.c', b'int main() {}')])
 
368
        inner_tree.add(['foo.c', 'bar.c'])
 
369
        # can't commit files in different trees; sane error
 
370
        self.run_bzr('commit -m newstuff branch/foo.c .', retcode=3)
 
371
        # can commit to branch - records foo.c only
 
372
        self.run_bzr('commit -m newstuff branch/foo.c')
 
373
        # can commit to branch - records bar.c
 
374
        self.run_bzr('commit -m newstuff branch')
 
375
        # No changes left
 
376
        self.run_bzr_error(["No changes to commit"], 'commit -m newstuff branch')
 
377
 
 
378
    def test_out_of_date_tree_commit(self):
 
379
        # check we get an error code and a clear message committing with an out
 
380
        # of date checkout
 
381
        tree = self.make_branch_and_tree('branch')
 
382
        # make a checkout
 
383
        checkout = tree.branch.create_checkout('checkout', lightweight=True)
 
384
        # commit to the original branch to make the checkout out of date
 
385
        tree.commit('message branch', allow_pointless=True)
 
386
        # now commit to the checkout should emit
 
387
        # ERROR: Out of date with the branch, 'brz update' is suggested
 
388
        output = self.run_bzr('commit --unchanged -m checkout_message '
 
389
                             'checkout', retcode=3)
 
390
        self.assertEqual(output,
 
391
                         ('',
 
392
                          "brz: ERROR: Working tree is out of date, please "
 
393
                          "run 'brz update'.\n"))
 
394
 
 
395
    def test_local_commit_unbound(self):
 
396
        # a --local commit on an unbound branch is an error
 
397
        self.make_branch_and_tree('.')
 
398
        out, err = self.run_bzr('commit --local', retcode=3)
 
399
        self.assertEqualDiff('', out)
 
400
        self.assertEqualDiff('brz: ERROR: Cannot perform local-only commits '
 
401
                             'on unbound branches.\n', err)
 
402
 
 
403
    def test_commit_a_text_merge_in_a_checkout(self):
 
404
        # checkouts perform multiple actions in a transaction across bond
 
405
        # branches and their master, and have been observed to fail in the
 
406
        # past. This is a user story reported to fail in bug #43959 where
 
407
        # a merge done in a checkout (using the update command) failed to
 
408
        # commit correctly.
 
409
        trunk = self.make_branch_and_tree('trunk')
 
410
 
 
411
        u1 = trunk.branch.create_checkout('u1')
 
412
        self.build_tree_contents([('u1/hosts', b'initial contents\n')])
 
413
        u1.add('hosts')
 
414
        self.run_bzr('commit -m add-hosts u1')
 
415
 
 
416
        u2 = trunk.branch.create_checkout('u2')
 
417
        self.build_tree_contents([('u2/hosts', b'altered in u2\n')])
 
418
        self.run_bzr('commit -m checkin-from-u2 u2')
 
419
 
 
420
        # make an offline commits
 
421
        self.build_tree_contents([('u1/hosts', b'first offline change in u1\n')])
 
422
        self.run_bzr('commit -m checkin-offline --local u1')
 
423
 
 
424
        # now try to pull in online work from u2, and then commit our offline
 
425
        # work as a merge
 
426
        # retcode 1 as we expect a text conflict
 
427
        self.run_bzr('update u1', retcode=1)
 
428
        self.assertFileEqual(b'''\
 
429
<<<<<<< TREE
 
430
first offline change in u1
 
431
=======
 
432
altered in u2
 
433
>>>>>>> MERGE-SOURCE
 
434
''',
 
435
                             'u1/hosts')
 
436
 
 
437
        self.run_bzr('resolved u1/hosts')
 
438
        # add a text change here to represent resolving the merge conflicts in
 
439
        # favour of a new version of the file not identical to either the u1
 
440
        # version or the u2 version.
 
441
        self.build_tree_contents([('u1/hosts', b'merge resolution\n')])
 
442
        self.run_bzr('commit -m checkin-merge-of-the-offline-work-from-u1 u1')
 
443
 
 
444
    def test_commit_exclude_excludes_modified_files(self):
 
445
        """Commit -x foo should ignore changes to foo."""
 
446
        tree = self.make_branch_and_tree('.')
 
447
        self.build_tree(['a', 'b', 'c'])
 
448
        tree.smart_add(['.'])
 
449
        out, err = self.run_bzr(['commit', '-m', 'test', '-x', 'b'])
 
450
        self.assertFalse('added b' in out)
 
451
        self.assertFalse('added b' in err)
 
452
        # If b was excluded it will still be 'added' in status.
 
453
        out, err = self.run_bzr(['added'])
 
454
        self.assertEqual('b\n', out)
 
455
        self.assertEqual('', err)
 
456
 
 
457
    def test_commit_exclude_twice_uses_both_rules(self):
 
458
        """Commit -x foo -x bar should ignore changes to foo and bar."""
 
459
        tree = self.make_branch_and_tree('.')
 
460
        self.build_tree(['a', 'b', 'c'])
 
461
        tree.smart_add(['.'])
 
462
        out, err = self.run_bzr(['commit', '-m', 'test', '-x', 'b', '-x', 'c'])
 
463
        self.assertFalse('added b' in out)
 
464
        self.assertFalse('added c' in out)
 
465
        self.assertFalse('added b' in err)
 
466
        self.assertFalse('added c' in err)
 
467
        # If b was excluded it will still be 'added' in status.
 
468
        out, err = self.run_bzr(['added'])
 
469
        self.assertTrue('b\n' in out)
 
470
        self.assertTrue('c\n' in out)
 
471
        self.assertEqual('', err)
 
472
 
 
473
    def test_commit_respects_spec_for_removals(self):
 
474
        """Commit with a file spec should only commit removals that match"""
 
475
        t = self.make_branch_and_tree('.')
 
476
        self.build_tree(['file-a', 'dir-a/', 'dir-a/file-b'])
 
477
        t.add(['file-a', 'dir-a', 'dir-a/file-b'])
 
478
        t.commit('Create')
 
479
        t.remove(['file-a', 'dir-a/file-b'])
 
480
        result = self.run_bzr('commit . -m removed-file-b',
 
481
                              working_dir='dir-a')[1]
 
482
        self.assertNotContainsRe(result, 'file-a')
 
483
        result = self.run_bzr('status', working_dir='dir-a')[0]
 
484
        self.assertContainsRe(result, 'removed:\n  file-a')
 
485
 
 
486
    def test_strict_commit(self):
 
487
        """Commit with --strict works if everything is known"""
 
488
        ignores._set_user_ignores([])
 
489
        tree = self.make_branch_and_tree('tree')
 
490
        self.build_tree(['tree/a'])
 
491
        tree.add('a')
 
492
        # A simple change should just work
 
493
        self.run_bzr('commit --strict -m adding-a', working_dir='tree')
 
494
 
 
495
    def test_strict_commit_no_changes(self):
 
496
        """commit --strict gives "no changes" if there is nothing to commit"""
 
497
        tree = self.make_branch_and_tree('tree')
 
498
        self.build_tree(['tree/a'])
 
499
        tree.add('a')
 
500
        tree.commit('adding a')
 
501
 
 
502
        # With no changes, it should just be 'no changes'
 
503
        # Make sure that commit is failing because there is nothing to do
 
504
        self.run_bzr_error(['No changes to commit'],
 
505
                           'commit --strict -m no-changes',
 
506
                           working_dir='tree')
 
507
 
 
508
        # But --strict doesn't care if you supply --unchanged
 
509
        self.run_bzr('commit --strict --unchanged -m no-changes',
 
510
                     working_dir='tree')
 
511
 
 
512
    def test_strict_commit_unknown(self):
 
513
        """commit --strict fails if a file is unknown"""
 
514
        tree = self.make_branch_and_tree('tree')
 
515
        self.build_tree(['tree/a'])
 
516
        tree.add('a')
 
517
        tree.commit('adding a')
 
518
 
 
519
        # Add one file so there is a change, but forget the other
 
520
        self.build_tree(['tree/b', 'tree/c'])
 
521
        tree.add('b')
 
522
        self.run_bzr_error(['Commit refused because there are unknown files'],
 
523
                           'commit --strict -m add-b',
 
524
                           working_dir='tree')
 
525
 
 
526
        # --no-strict overrides --strict
 
527
        self.run_bzr('commit --strict -m add-b --no-strict',
 
528
                     working_dir='tree')
 
529
 
 
530
    def test_fixes_bug_output(self):
 
531
        """commit --fixes=lp:23452 succeeds without output."""
 
532
        tree = self.make_branch_and_tree('tree')
 
533
        self.build_tree(['tree/hello.txt'])
 
534
        tree.add('hello.txt')
 
535
        output, err = self.run_bzr(
 
536
            'commit -m hello --fixes=lp:23452 tree/hello.txt')
 
537
        self.assertEqual('', output)
 
538
        self.assertContainsRe(err, 'Committing to: .*\n'
 
539
                              'added hello\\.txt\n'
 
540
                              'Committed revision 1\\.\n')
 
541
 
 
542
    def test_fixes_bug_unicode(self):
 
543
        """commit --fixes=lp:unicode succeeds without output."""
 
544
        tree = self.make_branch_and_tree('tree')
 
545
        self.build_tree(['tree/hello.txt'])
 
546
        tree.add('hello.txt')
 
547
        output, err = self.run_bzr_raw(
 
548
            ['commit', '-m', 'hello',
 
549
             u'--fixes=generic:\u20ac', 'tree/hello.txt'],
 
550
            encoding='utf-8', retcode=3)
 
551
        self.assertEqual(b'', output)
 
552
        self.assertContainsRe(err,
 
553
            b'brz: ERROR: Unrecognized bug generic:\xe2\x82\xac\\. Commit refused.\n')
 
554
 
 
555
    def test_no_bugs_no_properties(self):
 
556
        """If no bugs are fixed, the bugs property is not set.
 
557
 
 
558
        see https://beta.launchpad.net/bzr/+bug/109613
 
559
        """
 
560
        tree = self.make_branch_and_tree('tree')
 
561
        self.build_tree(['tree/hello.txt'])
 
562
        tree.add('hello.txt')
 
563
        self.run_bzr('commit -m hello tree/hello.txt')
 
564
        # Get the revision properties, ignoring the branch-nick property, which
 
565
        # we don't care about for this test.
 
566
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
567
        properties = dict(last_rev.properties)
 
568
        del properties['branch-nick']
 
569
        self.assertFalse('bugs' in properties)
 
570
 
 
571
    def test_bugs_sets_property(self):
 
572
        """commit --bugs=lp:234 sets the lp:234 revprop to 'related'."""
 
573
        tree = self.make_branch_and_tree('tree')
 
574
        self.build_tree(['tree/hello.txt'])
 
575
        tree.add('hello.txt')
 
576
        self.run_bzr('commit -m hello --bugs=lp:234 tree/hello.txt')
 
577
 
 
578
        # Get the revision properties, ignoring the branch-nick property, which
 
579
        # we don't care about for this test.
 
580
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
581
        properties = dict(last_rev.properties)
 
582
        del properties[u'branch-nick']
 
583
 
 
584
        self.assertEqual({u'bugs': 'https://launchpad.net/bugs/234 related'},
 
585
                         properties)
 
586
 
 
587
    def test_fixes_bug_sets_property(self):
 
588
        """commit --fixes=lp:234 sets the lp:234 revprop to 'fixed'."""
 
589
        tree = self.make_branch_and_tree('tree')
 
590
        self.build_tree(['tree/hello.txt'])
 
591
        tree.add('hello.txt')
 
592
        self.run_bzr('commit -m hello --fixes=lp:234 tree/hello.txt')
 
593
 
 
594
        # Get the revision properties, ignoring the branch-nick property, which
 
595
        # we don't care about for this test.
 
596
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
597
        properties = dict(last_rev.properties)
 
598
        del properties[u'branch-nick']
 
599
 
 
600
        self.assertEqual({u'bugs': 'https://launchpad.net/bugs/234 fixed'},
 
601
                         properties)
 
602
 
 
603
    def test_fixes_multiple_bugs_sets_properties(self):
 
604
        """--fixes can be used more than once to show that bugs are fixed."""
 
605
        tree = self.make_branch_and_tree('tree')
 
606
        self.build_tree(['tree/hello.txt'])
 
607
        tree.add('hello.txt')
 
608
        self.run_bzr('commit -m hello --fixes=lp:123 --fixes=lp:235'
 
609
                     ' tree/hello.txt')
 
610
 
 
611
        # Get the revision properties, ignoring the branch-nick property, which
 
612
        # we don't care about for this test.
 
613
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
614
        properties = dict(last_rev.properties)
 
615
        del properties['branch-nick']
 
616
 
 
617
        self.assertEqual(
 
618
            {u'bugs': 'https://launchpad.net/bugs/123 fixed\n'
 
619
                     'https://launchpad.net/bugs/235 fixed'},
 
620
            properties)
 
621
 
 
622
    def test_fixes_bug_with_alternate_trackers(self):
 
623
        """--fixes can be used on a properly configured branch to mark bug
 
624
        fixes on multiple trackers.
 
625
        """
 
626
        tree = self.make_branch_and_tree('tree')
 
627
        tree.branch.get_config().set_user_option(
 
628
            'trac_twisted_url', 'http://twistedmatrix.com/trac')
 
629
        self.build_tree(['tree/hello.txt'])
 
630
        tree.add('hello.txt')
 
631
        self.run_bzr('commit -m hello --fixes=lp:123 --fixes=twisted:235 tree/')
 
632
 
 
633
        # Get the revision properties, ignoring the branch-nick property, which
 
634
        # we don't care about for this test.
 
635
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
636
        properties = dict(last_rev.properties)
 
637
        del properties['branch-nick']
 
638
 
 
639
        self.assertEqual(
 
640
            {'bugs': 'https://launchpad.net/bugs/123 fixed\n'
 
641
                     'http://twistedmatrix.com/trac/ticket/235 fixed'},
 
642
            properties)
 
643
 
 
644
    def test_fixes_unknown_bug_prefix(self):
 
645
        tree = self.make_branch_and_tree('tree')
 
646
        self.build_tree(['tree/hello.txt'])
 
647
        tree.add('hello.txt')
 
648
        self.run_bzr_error(
 
649
            ["Unrecognized bug %s. Commit refused." % 'xxx:123'],
 
650
            'commit -m add-b --fixes=xxx:123',
 
651
            working_dir='tree')
 
652
 
 
653
    def test_fixes_bug_with_default_tracker(self):
 
654
        """commit --fixes=234 uses the default bug tracker."""
 
655
        tree = self.make_branch_and_tree('tree')
 
656
        self.build_tree(['tree/hello.txt'])
 
657
        tree.add('hello.txt')
 
658
        self.run_bzr_error(
 
659
            ["brz: ERROR: No tracker specified for bug 123. Use the form "
 
660
            "'tracker:id' or specify a default bug tracker using the "
 
661
            "`bugtracker` option.\n"
 
662
            "See \"brz help bugs\" for more information on this feature. "
 
663
            "Commit refused."],
 
664
            'commit -m add-b --fixes=123',
 
665
            working_dir='tree')
 
666
        tree.branch.get_config_stack().set("bugtracker", "lp")
 
667
        self.run_bzr('commit -m hello --fixes=234 tree/hello.txt')
 
668
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
669
        self.assertEqual('https://launchpad.net/bugs/234 fixed',
 
670
                         last_rev.properties['bugs'])
 
671
 
 
672
    def test_fixes_invalid_bug_number(self):
 
673
        tree = self.make_branch_and_tree('tree')
 
674
        self.build_tree(['tree/hello.txt'])
 
675
        tree.add('hello.txt')
 
676
        self.run_bzr_error(
 
677
            ["Did not understand bug identifier orange: Must be an integer. "
 
678
             "See \"brz help bugs\" for more information on this feature.\n"
 
679
             "Commit refused."],
 
680
            'commit -m add-b --fixes=lp:orange',
 
681
            working_dir='tree')
 
682
 
 
683
    def test_fixes_invalid_argument(self):
 
684
        """Raise an appropriate error when the fixes argument isn't tag:id."""
 
685
        tree = self.make_branch_and_tree('tree')
 
686
        self.build_tree(['tree/hello.txt'])
 
687
        tree.add('hello.txt')
 
688
        self.run_bzr_error(
 
689
            [r"Invalid bug orange:apples:bananas. Must be in the form of "
 
690
             r"'tracker:id'\. See \"brz help bugs\" for more information on "
 
691
             r"this feature.\nCommit refused\."],
 
692
            'commit -m add-b --fixes=orange:apples:bananas',
 
693
            working_dir='tree')
 
694
 
 
695
    def test_no_author(self):
 
696
        """If the author is not specified, the author property is not set."""
 
697
        tree = self.make_branch_and_tree('tree')
 
698
        self.build_tree(['tree/hello.txt'])
 
699
        tree.add('hello.txt')
 
700
        self.run_bzr( 'commit -m hello tree/hello.txt')
 
701
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
702
        properties = last_rev.properties
 
703
        self.assertFalse('author' in properties)
 
704
 
 
705
    def test_author_sets_property(self):
 
706
        """commit --author='John Doe <jdoe@example.com>' sets the author
 
707
           revprop.
 
708
        """
 
709
        tree = self.make_branch_and_tree('tree')
 
710
        self.build_tree(['tree/hello.txt'])
 
711
        tree.add('hello.txt')
 
712
        self.run_bzr(["commit", '-m', 'hello',
 
713
                      '--author', u'John D\xf6 <jdoe@example.com>',
 
714
                     "tree/hello.txt"])
 
715
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
716
        properties = last_rev.properties
 
717
        self.assertEqual(u'John D\xf6 <jdoe@example.com>', properties['authors'])
 
718
 
 
719
    def test_author_no_email(self):
 
720
        """Author's name without an email address is allowed, too."""
 
721
        tree = self.make_branch_and_tree('tree')
 
722
        self.build_tree(['tree/hello.txt'])
 
723
        tree.add('hello.txt')
 
724
        out, err = self.run_bzr("commit -m hello --author='John Doe' "
 
725
                                "tree/hello.txt")
 
726
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
727
        properties = last_rev.properties
 
728
        self.assertEqual('John Doe', properties['authors'])
 
729
 
 
730
    def test_multiple_authors(self):
 
731
        """Multiple authors can be specyfied, and all are stored."""
 
732
        tree = self.make_branch_and_tree('tree')
 
733
        self.build_tree(['tree/hello.txt'])
 
734
        tree.add('hello.txt')
 
735
        out, err = self.run_bzr("commit -m hello --author='John Doe' "
 
736
                                "--author='Jane Rey' tree/hello.txt")
 
737
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
738
        properties = last_rev.properties
 
739
        self.assertEqual('John Doe\nJane Rey', properties['authors'])
 
740
 
 
741
    def test_commit_time(self):
 
742
        tree = self.make_branch_and_tree('tree')
 
743
        self.build_tree(['tree/hello.txt'])
 
744
        tree.add('hello.txt')
 
745
        out, err = self.run_bzr("commit -m hello "
 
746
            "--commit-time='2009-10-10 08:00:00 +0100' tree/hello.txt")
 
747
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
748
        self.assertEqual(
 
749
            'Sat 2009-10-10 08:00:00 +0100',
 
750
            osutils.format_date(last_rev.timestamp, last_rev.timezone))
 
751
        
 
752
    def test_commit_time_bad_time(self):
 
753
        tree = self.make_branch_and_tree('tree')
 
754
        self.build_tree(['tree/hello.txt'])
 
755
        tree.add('hello.txt')
 
756
        out, err = self.run_bzr("commit -m hello "
 
757
            "--commit-time='NOT A TIME' tree/hello.txt", retcode=3)
 
758
        self.assertStartsWith(
 
759
            err, "brz: ERROR: Could not parse --commit-time:")
 
760
 
 
761
    def test_commit_time_missing_tz(self):
 
762
        tree = self.make_branch_and_tree('tree')
 
763
        self.build_tree(['tree/hello.txt'])
 
764
        tree.add('hello.txt')
 
765
        out, err = self.run_bzr("commit -m hello "
 
766
            "--commit-time='2009-10-10 08:00:00' tree/hello.txt", retcode=3)
 
767
        self.assertStartsWith(
 
768
            err, "brz: ERROR: Could not parse --commit-time:")
 
769
        # Test that it is actually checking and does not simply crash with
 
770
        # some other exception
 
771
        self.assertContainsString(err, "missing a timezone offset")
 
772
 
 
773
    def test_partial_commit_with_renames_in_tree(self):
 
774
        # this test illustrates bug #140419
 
775
        t = self.make_branch_and_tree('.')
 
776
        self.build_tree(['dir/', 'dir/a', 'test'])
 
777
        t.add(['dir/', 'dir/a', 'test'])
 
778
        t.commit('initial commit')
 
779
        # important part: file dir/a should change parent
 
780
        # and should appear before old parent
 
781
        # then during partial commit we have error
 
782
        # parent_id {dir-XXX} not in inventory
 
783
        t.rename_one('dir/a', 'a')
 
784
        self.build_tree_contents([('test', b'changes in test')])
 
785
        # partial commit
 
786
        out, err = self.run_bzr('commit test -m "partial commit"')
 
787
        self.assertEqual('', out)
 
788
        self.assertContainsRe(err, r'modified test\nCommitted revision 2.')
 
789
 
 
790
    def test_commit_readonly_checkout(self):
 
791
        # https://bugs.launchpad.net/bzr/+bug/129701
 
792
        # "UnlockableTransport error trying to commit in checkout of readonly
 
793
        # branch"
 
794
        self.make_branch('master')
 
795
        master = ControlDir.open_from_transport(
 
796
            self.get_readonly_transport('master')).open_branch()
 
797
        master.create_checkout('checkout')
 
798
        out, err = self.run_bzr(['commit', '--unchanged', '-mfoo', 'checkout'],
 
799
            retcode=3)
 
800
        self.assertContainsRe(err,
 
801
            r'^brz: ERROR: Cannot lock.*readonly transport')
 
802
 
 
803
    def setup_editor(self):
 
804
        # Test that commit template hooks work
 
805
        if sys.platform == "win32":
 
806
            with open('fed.bat', 'w') as f:
 
807
                f.write('@rem dummy fed')
 
808
            self.overrideEnv('BRZ_EDITOR', "fed.bat")
 
809
        else:
 
810
            with open('fed.sh', 'wb') as f:
 
811
                f.write(b'#!/bin/sh\n')
 
812
            os.chmod('fed.sh', 0o755)
 
813
            self.overrideEnv('BRZ_EDITOR', "./fed.sh")
 
814
 
 
815
    def setup_commit_with_template(self):
 
816
        self.setup_editor()
 
817
        msgeditor.hooks.install_named_hook("commit_message_template",
 
818
                lambda commit_obj, msg: "save me some typing\n", None)
 
819
        tree = self.make_branch_and_tree('tree')
 
820
        self.build_tree(['tree/hello.txt'])
 
821
        tree.add('hello.txt')
 
822
        return tree
 
823
 
 
824
    def test_edit_empty_message(self):
 
825
        tree = self.make_branch_and_tree('tree')
 
826
        self.setup_editor()
 
827
        self.build_tree(['tree/hello.txt'])
 
828
        tree.add('hello.txt')
 
829
        out, err = self.run_bzr("commit tree/hello.txt", retcode=3,
 
830
            stdin="y\n")
 
831
        self.assertContainsRe(err,
 
832
            "brz: ERROR: Empty commit message specified")
 
833
 
 
834
    def test_commit_hook_template_accepted(self):
 
835
        tree = self.setup_commit_with_template()
 
836
        out, err = self.run_bzr("commit tree/hello.txt", stdin="y\n")
 
837
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
838
        self.assertEqual('save me some typing\n', last_rev.message)
 
839
 
 
840
    def test_commit_hook_template_rejected(self):
 
841
        tree = self.setup_commit_with_template()
 
842
        expected = tree.last_revision()
 
843
        out, err = self.run_bzr_error(["Empty commit message specified."
 
844
                  " Please specify a commit message with either"
 
845
                  " --message or --file or leave a blank message"
 
846
                  " with --message \"\"."],
 
847
            "commit tree/hello.txt", stdin="n\n")
 
848
        self.assertEqual(expected, tree.last_revision())
 
849
 
 
850
    def test_set_commit_message(self):
 
851
        msgeditor.hooks.install_named_hook("set_commit_message",
 
852
                lambda commit_obj, msg: "save me some typing\n", None)
 
853
        tree = self.make_branch_and_tree('tree')
 
854
        self.build_tree(['tree/hello.txt'])
 
855
        tree.add('hello.txt')
 
856
        out, err = self.run_bzr("commit tree/hello.txt")
 
857
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
858
        self.assertEqual('save me some typing\n', last_rev.message)
 
859
 
 
860
    def test_commit_without_username(self):
 
861
        """Ensure commit error if username is not set.
 
862
        """
 
863
        self.run_bzr(['init', 'foo'])
 
864
        with open('foo/foo.txt', 'w') as f:
 
865
            f.write('hello')
 
866
        self.run_bzr(['add'], working_dir='foo')
 
867
        self.overrideEnv('EMAIL', None)
 
868
        self.overrideEnv('BRZ_EMAIL', None)
 
869
        # Also, make sure that it's not inferred from mailname.
 
870
        self.overrideAttr(config, '_auto_user_id',
 
871
            lambda: (None, None))
 
872
        self.run_bzr_error(
 
873
            ['Unable to determine your name'],
 
874
            ['commit', '-m', 'initial'], working_dir='foo')
 
875
 
 
876
    def test_commit_recursive_checkout(self):
 
877
        """Ensure that a commit to a recursive checkout fails cleanly.
 
878
        """
 
879
        self.run_bzr(['init', 'test_branch'])
 
880
        self.run_bzr(['checkout', 'test_branch', 'test_checkout'])
 
881
        self.run_bzr(['bind', '.'], working_dir='test_checkout') # bind to self
 
882
        with open('test_checkout/foo.txt', 'w') as f:
 
883
            f.write('hello')
 
884
        self.run_bzr(['add'], working_dir='test_checkout')
 
885
        out, err = self.run_bzr_error(
 
886
            ['Branch.*test_checkout.*appears to be bound to itself'],
 
887
            ['commit', '-m', 'addedfoo'], working_dir='test_checkout')
 
888
 
 
889
    def test_mv_dirs_non_ascii(self):
 
890
        """Move directory with non-ascii name and containing files.
 
891
 
 
892
        Regression test for bug 185211.
 
893
        """
 
894
        tree = self.make_branch_and_tree('.')
 
895
        self.build_tree([u'abc\xa7/', u'abc\xa7/foo'])
 
896
 
 
897
        tree.add([u'abc\xa7/', u'abc\xa7/foo'])
 
898
        tree.commit('checkin')
 
899
 
 
900
        tree.rename_one(u'abc\xa7', 'abc')
 
901
 
 
902
        self.run_bzr('ci -m "non-ascii mv"')
 
903
 
 
904
 
 
905
class TestSmartServerCommit(TestCaseWithTransport):
 
906
 
 
907
    def test_commit_to_lightweight(self):
 
908
        self.setup_smart_server_with_call_log()
 
909
        t = self.make_branch_and_tree('from')
 
910
        for count in range(9):
 
911
            t.commit(message='commit %d' % count)
 
912
        out, err = self.run_bzr(['checkout', '--lightweight', self.get_url('from'),
 
913
            'target'])
 
914
        self.reset_smart_call_log()
 
915
        self.build_tree(['target/afile'])
 
916
        self.run_bzr(['add', 'target/afile'])
 
917
        out, err = self.run_bzr(['commit', '-m', 'do something', 'target'])
 
918
        # This figure represent the amount of work to perform this use case. It
 
919
        # is entirely ok to reduce this number if a test fails due to rpc_count
 
920
        # being too low. If rpc_count increases, more network roundtrips have
 
921
        # become necessary for this use case. Please do not adjust this number
 
922
        # upwards without agreement from bzr's network support maintainers.
 
923
        self.assertLength(211, self.hpss_calls)
 
924
        self.assertLength(2, self.hpss_connections)
 
925
        self.expectFailure("commit still uses VFS calls",
 
926
            self.assertThat, self.hpss_calls, ContainsNoVfsCalls)